Convert a struct to vector of bytes

2019-05-27 05:07发布

问题:

In my c++ application I have this struct

typedef struct 
{
int a;
int b;
char *c
}MyStruct

and I have this instance:

MyStruct s;

also I have this definition:

vector<byte> buffer;

I would like to insert\convert the "s" struct to the buffer vector.

what is the best way to do it in c++?

thanks

回答1:

The best way is by using the range copy constructor and a low-level cast to retrieve a pointer to the memory of the structure:

auto ptr = reinterpret_cast<byte*>(&s);
auto buffer = vector<byte>(ptr, ptr + sizeof s);

To go the other way, you can just cast the byte buffer to the target type (but it needs to be the same type, otherwise you’re violating strict aliasing):

auto p_obj = reinterpret_cast<obj_t*>(&buffer[0]);

However, for indices ≠ 0 (and I guess technically also for index = 0, but this seems unlikely) beware of mismatching memory alignment. A safer way is therefore to first copy the buffer into a properly aligned storage, and to access pointers from there.