container_of宏定义解析

container_of宏,定义kernel.h中:

 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) );})
container_of在Linux Kernel中的应用非常广泛, 它用于从结构体成员获取结构体的地址。定义中:
typeof:这是gcc的C语言扩展保留字, 用于从变量获取类型
offsetof在stddef.h中, 用来获得一个结构体成员的相对偏移量
1 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
offsetof 是怎么做到的呢?它把0地址强制转化成了TYPE*类型,然后将它的MEMBER成员的地址转化为size_t类型。也就是说如果一个类型为TYPE的结 构体地址从0开始,那么它的MEMBER成员的地址就是MEMBER成员与TYPE类型地址之间的相对偏移量(以char计数的)。
开始解析container_of:
这个宏传入3个参数:ptr(type的成员的地址),type(结构体类型),member(成员的名称)
第一行:const typeof( ((type *)0)->member ) *__mptr = (ptr);
首 先要正确的取得member地址,因为参数中没有传入member的类型,所以要通过typeof( ((type *)0)->member ) *搞出member的类型,typeof括号中的式子与offsetof中的作用类似,取得了member之后再使用typeof得到它的类型。所以第一 行的结果就是__mptr是member类型的指向ptr地址的常量指针。
第二行:(type *)( (char *)__mptr - offsetof(type,member) );
取得了member的地址之后,只要把它减去member相对于结构体的偏移量,就可以得到结构体的地址了。最后,再把这个地址转化成type*,就完成了整个逻辑。
原文地址:https://www.cnblogs.com/zongfanstudy/p/13708250.html