转换(无效*)到std ::矢量< unsigned char型> [英] Converting (void*) to std::vector<unsigned char>

查看:131
本文介绍了转换(无效*)到std ::矢量< unsigned char型>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个(无效*)缓冲,我需要转换为的std ::矢量< unsigned char型> 之前,我可以通过它。不幸的是,我的C ++的铸造技能稍微弱。有什么建议?

I have a (void*) buffer that I need to convert to std::vector<unsigned char> before I can pass it on. Unfortunately, my C++ casting skills a little weak. Any suggestions?

推荐答案

您需要的缓冲区的长度。一旦你这样做,我们可以做到这一点:

You will need the length of the buffer. Once you do, we can do this:

unsigned char *charBuf = (unsigned char*)voidBuf;
/* create a vector by copying out the contents of charBuf */
std::vector<unsigned char> v(charBuf, charBuf + len);

好吧,评论让我开始对我为什么不使用 reinter pret_cast


      
  • 在C ++中,C样式转换是一个方便的功能 - 它要求编译器选择转换的最安全,最便携的形式在一组可用的转换操作符的

  • In C++, the C-style cast is a convenience function -- it asks the compiler to choose the safest and most portable form of conversion over the set of available cast operators.

reinter pret_cast 是实现定义,应该永远是你心中的最后一件事(和使用时,你一定做一个非便携式事情明知)。

The reinterpret_cast is implementation defined and should always be the last thing on your mind (and used when you are necessarily doing a non-portable thing knowingly).

无符号不改变类型)的char * 和<$ C之间的转换$ C>无效* 是可移植的(你可以实际使用的static_cast 如果你真的挑剔)。

The conversion between (unsigned doesn't change the type) char * and void * is portable (you could actually use static_cast if you are really picky).

与C样式转换的问题是:增加了灵活性可能会导致心痛,当指针类型更改

The problem with the C-style cast is: the added flexibility can cause heartaches when the pointer type changes.

注意:我同意不铸造尽可能多的一般惯例。然而,如果没有提供的任何来源,这是我能做的最好的。

Note: I agree with the general convention of not casting as much as possible. However, without any source provided, this is the best I could do.

这篇关于转换(无效*)到std ::矢量&lt; unsigned char型&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆