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++ 结构紧密包装


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09