Convert a struct to vector of bytes

前端 未结 1 1041
北荒
北荒 2021-02-10 03:38

In my c++ application I have this struct

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

and I have this instance:

MyStruct s         


        
相关标签:
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.

    0 讨论(0)
提交回复
热议问题