强制C ++结构紧密包装 [英] Force C++ structure to pack tightly

查看:66
本文介绍了强制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.

是否有一种方法可以强制将结构设置为

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

例如:

struct {
    short a;
    int b;
}

以上结构为8个字节:2个表示 short a ,填充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)){ int 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 ++结构紧密包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆