在我的c ++应用程序中,我有这个结构
typedef struct
{
int a;
int b;
char *c
}MyStruct
我有这个例子:
MyStruct s;
我也有这个定义:
vector<byte> buffer;
我想插入\将“s”结构转换为缓冲区向量。
在c ++中最好的方法是什么?
感谢
答案 0 :(得分:11)
最好的方法是使用range copy constructor和低级别强制转换来检索指向结构内存的指针:
auto ptr = reinterpret_cast<byte*>(&s);
auto buffer = vector<byte>(ptr, ptr + sizeof s);
换句话说,您可以将字节缓冲区强制转换为目标类型(但它必须是相同的类型,否则您将违反strict aliasing):< / p>
auto p_obj = reinterpret_cast<obj_t*>(&buffer[0]);
然而,对于索引≠0(我猜技术上也是索引= 0,但这似乎不太可能)注意不匹配memory alignment。因此,更安全的方法是首先将缓冲区复制到properly aligned storage,然后从那里访问指针。