且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是"包装"结构用C?

更新时间:2023-02-15 20:35:38

在定义的结构,编译器不允许添加垫(空格没有实际的数据),使成员陷入地址边界更易于访问的CPU

When structures are defined, the compiler is allowed to add paddings (spaces without actual data) so that members fall in address boundaries that are easier to access for the CPU.

例如,一个32位CPU上,32位成员应该是为了多4个字节被有效地访问(读取和写入)地址启动。以下结构定义将两个部件之间的16位填充,使得第二构件落在正确地址边界

For example, on a 32-bit CPU, 32-bit members should start at addresses that are multiple of 4 bytes in order to be efficiently accessed (read and written). The following structure definition adds a 16-bit padding between both members, so that the second member falls in a proper address boundary:

struct S {
    int16_t member1;
    int32_t member2;
};

在32位架构在上述结构的内存结构( =填充):

+---------+---------+
| m1 |~~~~|   m2    |
+---------+---------+

当结构已压缩,这些补白不插入。编译器生成更code(运行速度较慢)提取不结盟数据成员,也写信给他们。

When a structure is packed, these paddings are not inserted. The compiler has to generate more code (which runs slower) to extract the non-aligned data members, and also to write to them.

的相同的结构,包装时,会出现在内存中是这样的:

The same structure, when packed, will appear in memory as something like:

+---------+---------+
| m1 |   m2    |~~~~
+---------+---------+