C struct __attribute__ ((__packed__))

__packed__ 主要用于C/C++ 结构体中内存是否对齐
例如

struct st_packed {
    int s0;
    uint8_t s1;
    int s2;
} __attribute__ ((__packed__));
struct st_align {
    int s0;
    uint8_t s1;
    int s2;
};

sizeof(st_packed) 9
sizeof(st_align) 12

比较适合在申请一块内存时候作为头部结构体
例如

struct st_proto {
    uint8_t version;
    uint8_t type;
    int size;
    uint8_t data[];
} __attribute__ ((__packed__));
struct st_data {
    int flag;
    int res_code;
} __attribute__ ((__packed__));
struct st_com {
    st_proto proto;
    st_data data;
} __attribute__ ((__packed__));

这样的结构体结构紧密,适合做自定义二进制协议,可以直接用于网络发送(需要注意把int等类型等转为网络字节序)

posted @ 2020-03-07 16:56  stdpain  阅读(820)  评论(0编辑  收藏  举报