Struct padding in C++

后端 未结 4 1019
误落风尘
误落风尘 2020-11-22 09:11

If I have a struct in C++, is there no way to safely read/write it to a file that is cross-platform/compiler compatible?

Because if I understand correct

4条回答
  •  梦谈多话
    2020-11-22 10:00

    If you have the opportunity to design the struct yourself, it should be possible. The basic idea is that you should design it so that there would be no need to insert pad bytes into it. the second trick is that you must handle differences in endianess.

    I'll describe how to construct the struct using scalars, but the you should be able to use nested structs, as long as you would apply the same design for each included struct.

    First, a basic fact in C and C++ is that the alignment of a type can not exceed the size of the type. If it would, then it would not be possible to allocate memory using malloc(N*sizeof(the_type)).

    Layout the struct, starting with the largest types.

     struct
     {
       uint64_t alpha;
       uint32_t beta;
       uint32_t gamma;
       uint8_t  delta;
    

    Next, pad out the struct manually, so that in the end you will match up the largest type:

       uint8_t  pad8[3];    // Match uint32_t
       uint32_t pad32;      // Even number of uint32_t
     }
    

    Next step is to decide if the struct should be stored in little or big endian format. The best way is to "swap" all the element in situ before writing or after reading the struct, if the storage format does not match the endianess of the host system.

提交回复
热议问题