0%

有意思的代码片段

遇见的一些有意思的代码片段

###1. czmq3.0[c]

//Create a new chunk of the specified size. If you specify the data, it is
//copied into the chunk. If you do not specify the data, the chunk is
//allocated and left emtpy, and you can then add data using zchunk_append.
zchunk_t *zchunk_new (const void *data, size_t size){
    zchunk_t *self = (zchunk_t *) malloc( sizeof(zchunk_t) + size);
    if(self){
        self->tag = ZCHUNK_TAG;
        self->size = 0;
        self->max_size = size;
        self->consumed = 0;
        self->data = (byte *)self + sizeof(zchunk_t);//需要深入理解结构体的内存摆放方式啊
        if(data){
            self->size = size;
            memcpy(self->data, data, size);
        }
    }
    return self;
}

###2. nginx[c]
#define offsetof(type, member)(size_t)&(((type *)0)->member)
通过把0地址转换成结构体类型指针,再取相应member的地址,就得到相应Member相对于该结构体指针的偏移量,

nginx中使用它来获取元素
#define ngx_queue_data(q, type, link) (type *)((u_char *)q - offsetof(type, link))