将(void*)转换为std :: vector <unsigned char>

Mik*_*las 14 c++ binary types casting

我有一个(void*)缓冲区,我需要转换为std::vector<unsigned char>我可以传递它之前.不幸的是,我的C++演员技能有点弱.有什么建议?

dir*_*tly 27

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

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

好的,评论让我开始为什么我没有使用reinterpret_cast:

  • 在C++中,C风格的强制转换是一种便利功能 - 它要求编译器在可用的强制转换运算符集上选择最安全,最便携的转换形式.

  • 该reinterpret_cast是实现定义,应始终在您心中的最后一件事(和使用时,你必然是做非便携的事情故意).

  • 之间的转换(unsigned不改变类型)char *和void *为便携式(你实际上可以使用static_cast,如果你真的挑剔).

C风格转换的问题是:当指针类型改变时,增加的灵活性会导致心痛.

注意:我同意尽可能不投射的一般惯例.但是,如果没有提供任何来源,这是我能做的最好的.