“container_of”
/*
**先求得结构成员在与结构中的偏移量,然后根据成员变量的地址反过来得出属主结构变量的地址。
**
*/
#define container_of (ptr, type, member) ({ /
const typeof( ((type *)0)->member ) *__mptr = (ptr); /
(type *)( (char *)__mptr - offsetof(type,member) );})
((type *)0)->member,它将0地址强制"转换"为type结构的指针,再访问到type结构中的member成员。在container_of 宏中, 它用来给typeof()提供参数(typeof()是gcc的扩展,和sizeof()类似),以获得member成员的数据类型;在 offsetof()中,这个member成员的地址实际上就是type数据结构中member成员相对于结构变量的偏移量。
**先求得结构成员在与结构中的偏移量,然后根据成员变量的地址反过来得出属主结构变量的地址。
**
*/
#define container_of (ptr, type, member) ({ /
const typeof( ((type *)0)->member ) *__mptr = (ptr); /
(type *)( (char *)__mptr - offsetof(type,member) );})
((type *)0)->member,它将0地址强制"转换"为type结构的指针,再访问到type结构中的member成员。在container_of 宏中, 它用来给typeof()提供参数(typeof()是gcc的扩展,和sizeof()类似),以获得member成员的数据类型;在 offsetof()中,这个member成员的地址实际上就是type数据结构中member成员相对于结构变量的偏移量。
__mptr用作临时变量,making macro definitions "safe"。类似于
#define max(a,b) ((a) > (b) ? (a) : (b))
==〉
#define
maxint(a,b) /
({int _a = (a), _b = (b); _a > _b ? _a : _b;
})
本文详细解释了Linux内核中container_of宏的工作原理及其用途。该宏通过计算成员变量相对于其所属结构体的偏移量来获取结构体指针,这对于逆向定位结构体非常有用。
2521

被折叠的 条评论
为什么被折叠?



