站长论坛

标题: container_of宏解释 [打印本页]

作者: dingjianping    时间: 2007-9-13 19:31
标题: container_of宏解释
container_of宏,它的功能是得到包含某个结构成员的结构的指针:

其实现如下:

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({                      \
        const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
        (type *)( (char *)__mptr - offsetof(type,member) );})

    分析可知__mptr指向的是一个type结构里typeof(((type *)0)->member)类型member成员的指针,offsetof(type,member)是这个成员在结构中的偏移,单位是字节,所以为了计算type结构的起始地址,__mptr减去它自己的偏移。




欢迎光临 站长论坛 (http://www.tzlink.com/bbs/) Powered by Discuz! X3.2