Linux内核源码中container_of详解


关于container_of的用法,可参考  其实就是解决了”如何通过结构中的某个变量的地址获取结构本身的指针“这样的问题。container_of实现了根据一个结构体变量中的一个成员变量的指针来获取指向整个结构体变量的指针的功能。

首先container_of出现在linux/kernel.h中。定义如下:

[cpp]

  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) );}) 

typeof( ((type *)0)->member ) *__mptr 就是声明了一个指向其
我们在看一下offset的定义,在linux/stddef.h中。定义如下:

[cpp]

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

offset顾名思义就是获得该成员变量基于其包含体地址的偏移量。先分析一下这个宏:
1. ( (TYPE *)0 ) 将零转型为TYPE类型指针; 
2. ((TYPE *)0)->MEMBER 访问结构中的数据成员; 
3. &( ( (TYPE *)0 )->MEMBER )取出数据成员的地址; 
4.(size_t)(&(((TYPE*)0)->MEMBER))结果转换类型。

有人可能感觉很不适应(TYPE *)0这种用法,把一个0转换成一个结构体指针是什么意思呢?其实就是声明了一个指向无物的指针,并告诉编译器这个指针式指向TYPE类型的,然后成员地址自然为偏移地址,因为成员地址-0还是成员地址。

最后把__mptr 强制类型转换为char*类型,保证指针相减时是以一个字节为单位进行相减的,保证了程序的正确性。

这样我们就可以利用container_of来根据一个成员变量的指针来获取指向整个结构体变量的指针,对于应用层程序而言,这种机制完全没有必要,但是对于设备驱动程序而言,运用container_of就很有必要了。

相关内容