强制 C++ 结构紧密包装

2021-12-23 00:00:00 struct c++

我正在尝试读取二进制文件.问题是文件的创建者没有花时间将数据结构正确对齐到它们的自然边界,并且所有内容都被打包得很紧.这使得使用 C++ 结构读取数据变得困难.

I am attempting to read in a binary file. The problem is that the creator of the file took no time to properly align data structures to their natural boundaries and everything is packed tight. This makes it difficult to read the data using C++ structs.

有没有办法强制 struct 被压缩?

Is there a way to force a struct to be packed tight?

示例:

struct {
    short a;
    int b;
}

上述结构为8个字节:short a为2个,padding为2个,int b为4个.但是,在磁盘上,数据只有 6 个字节(没有 2 个字节的填充对齐)

The above structure is 8 bytes: 2 for short a, 2 for padding, 4 for int b. However, on disk, the data is only 6 bytes (not having the 2 bytes of padding for alignment)

请注意实际的数据结构是数千字节和许多字段,包括几个数组,所以我不想单独读取每个字段.

Please be aware the actual data structures are thousands of bytes and many fields, including a couple arrays, so I would prefer not to read each field individually.

推荐答案

如果你使用 GCC,你可以做 struct __attribute__ ((packed)) { short a;国际b;}

If you're using GCC, you can do struct __attribute__ ((packed)) { short a; int b; }

在 VC++ 上,您可以执行 #pragma pack(1).此选项GCC 也支持.

On VC++ you can do #pragma pack(1). This option is also supported by GCC.

#pragma pack(push, 1)
struct { short a; int b; }
#pragma pack(pop)

其他编译器可能会选择在没有填充的情况下对结构进行紧密打包.

Other compilers may have options to do a tight packing of the structure with no padding.

相关文章