Linux内核实现List二个关键的宏offsetof 和 container_of

来源:互联网 发布:lcdp0端口定义 编辑:程序博客网 时间:2024/04/29 20:53

二个宏定义在inux/kernel.h头文件

1.offsetof

offsetof宏的定义如下:

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

关键之处在于将地址0强制转换为type类型的指针,从而定位到member在结构体中偏移位置。编译器认为0是一个有效的地址,从而认为0是type指针的起始地址。

2.container_of

container_of宏定义如下:

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

container_of宏分为两部分,

1.const typeof( ((type *)0)->member ) *__mptr = (ptr);
通过typeof定义一个member指针类型的指针变量__mptr,(即__mptr是指向member类型的指针),并将__mptr赋值为ptr,关键之处将_mptr转换为member类型的指针。

2: (type )( (char )__mptr - offsetof(type,member) ),通过offsetof宏计算出member在type中的偏移,然后用member的实际地址__mptr减去偏移,得到type的起始地址,即指向type类型的指针。

0 0
原创粉丝点击