Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a struct to vector of bytes

Tags:

c++

struct

vector

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.

like image 730
gln Avatar asked Nov 26 '13 15:11

gln


1 Answers

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.

like image 111
Konrad Rudolph Avatar answered Sep 21 '22 23:09

Konrad Rudolph