分享

C 语言中 __packed

 My镜像站 2011-11-16

【正文】

简单的说,__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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多