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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With