Force C++ structure to pack tightly(强制 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.
这篇关于强制 C++ 结构紧密包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:强制 C++ 结构紧密包装


- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 近似搜索的工作原理 2021-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01