1 /*****************************
2 * container_of - cast a member of a structure out to the containing structure
功能:通过结构体成员找到成员所属结构体的首地址
3 * @ptr: the pointer to the member.
4 * @type: the type of the container struct this is embedded in.
5 * @member: the name of the member within the struct.
6 *
7 ************************************/
8 #define container_of(ptr, type, member) ({ \
9 const typeof(((type *)0)->member) * __mptr = (ptr); \
10 (type *)((char *)__mptr - offsetof(type, member)); })
typeof(((type *)0)->member) * __mptr = (ptr);
定义了一个type*类型的结构体子成员_mptr,并将ptr赋给它。(注:((type *)0)获得的是type的首地址)
(type *)((char *)__mptr - offsetof(type, member));
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER);
offsetof函数实现计算member相对于结构体type的偏移。
然后通过_mptr与其相减,即可获得mptr成员所属结构体的首地址。