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的地址值,这是内核中较为常见的用法。

 

 

相关文章:

  • 2022-12-23
  • 2021-10-08
  • 2021-10-05
  • 2022-12-23
  • 2022-12-23
  • 2021-09-21
  • 2021-05-21
猜你喜欢
  • 2021-07-02
  • 2021-06-22
  • 2021-06-20
  • 2022-01-05
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案