#define container_of(ptr, type, member) ({
\
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
这个宏的作用是利用一个结构体元素来计算结构体的起始地址。
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
ptr 是结构体的一个成员 type是结构体类型。就是将ptr 赋给 __mptr
(char *)__mptr 转换为地址
offsetof(type,member) );})
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
这个宏的关键点就在 (TYPE *)0 这里 ,将0 转换为TYPE结构 这个结构的起始地址将从0地址开始 然后指向MEMBER 就是这个成员的地址
然后(type *)( (char *)__mptr - offsetof(type,member) );})
成员的地址减去偏移的地址就是结构体的起始地址。
这个分析,从网络上而来,我只是记录。。。。并且学习。