7

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.

Guy Avraham
  • 3,482
  • 3
  • 38
  • 50
gln
  • 1,011
  • 5
  • 31
  • 61

1 Answers1

17

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    Nice answer. I have a different question: I need to do the "other way around": I have a vector which is filled with values (it's size is , say 100) , and I wish to compare the first 8 bytes of the vector with a given struct , that defined as follows: struct BlockInfoHeader { uint32_t magicHeader; uint32_t thread; uint64_t timestamp; // in microseconds since start of run uint64_t offset; uint32_t len; uint32_t blockIndex; uint32_t writeIndex; uint32_t seed; }; In order to compare the first 8 bytes of the vector with some values given in advance. – Guy Avraham May 11 '17 at 11:32
  • 1
    @GuyAvraham, please ask a new question, if you still have that doubt. – alx - recommends codidact Aug 26 '21 at 09:29