Linux内核中的container_of

Linux内核中的container_of

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

 其中typeof(x)是gcc对c的一种扩展,指的是x的类型。首先:(type*)0假设将0地址强制转换成传入的type类型,对type类型取其member成员,

通过typeof运算符,临时生成类型为typeof(x)__mptr的指针,且赋值为ptr。offsetof也是一个宏:

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

 指的是:((type *)0)->member距离type开始地址的字节数(即偏移量),因此:

(type *)( (char *)__mptr - offsetof(type,member) );

指的是:包含member类型的type的地址值,这是内核中较为常见的用法。

 

 

posted @ 2013-04-30 09:30  Richard Zhong  阅读(266)  评论(0编辑  收藏  举报