【正文】 简单的说,__packed 用于表示C语言中结构的压缩,即:没有填充和对齐。 定义如下: __packed struct P { ... }; struct P pp; /* pp is a packed struct */ __packed也可以定义为: struct my_unpacked_struct { char c; int i; } __attribute__ ((__packed__)); 如果一个结构体定义为 __packed,那么其子结构体也必须为__packed(如果有的话)例如: struct S {...}; __packed struct P {...}; struct T { struct S ss; /* OK */ struct P pp; /* OK */ }; __packed struct Q { struct S ss; /* faulted - sub-structs must be packed */ struct P pp; /* OK */ }; __packed struct P { char c; int x; }; __packed struct { struct P X; char z; struct P Y; }Q; 此时,Q的内存映像如下: <-------------------- Q --------------------> <-------- X --------> <-------- Y --------> +---+---+---+---+---+---+---+---+---+---+---+ byte | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10| | c | ------x------ | z | c | ------x------ | +---+---+---+---+---+---+---+---+---+---+---+ 参考文献: [1] http://www./tools/packed.shtml [2] http://axelio./2007/07/24/be-careful-with-packed-structures/ [3] http:///articles/gcc-packed-structures [4] http://en./wiki/Data_structure_alignment
|