Linux内核中的container_of宏


在看LDD第3章scull驱动的时候,遇到了container_of宏。这个东东会经常在内核中出现,原型定义在linux/include/linux/kernel.h中
  1. #define container_of(ptr, type, member) ({   \   
  2.     const typeof( ((type *)0)->member ) *__mptr = (ptr); \  
  3.     (type *)( (char *)__mptr - offsetof(type,member) );})  

为了说明这个宏是干什么用的,我编写了一个应用层的小程序。在应用层同样定义这样的一个宏,然后使用它。

  1. <span style="font-size:13px;"></span><pre class="cpp" name="code">#include<stdio.h>  
  2. #include<stdlib.h>   
  3. #include<stddef.h>   
  4.   
  5. #define container_of(ptr, type, member) ({                      \   
  6.         const typeof( ((type *)0)->member ) *__mptr = (ptr);    \  
  7.         (type *)( (char *)__mptr - offsetof(type,member) );})  
  8.   
  9. struct test  
  10. {  
  11.   int aint;  
  12.   char array[20];  
  13.   char *pointer;  
  14. };  
  15.   
  16. int main()  
  17. {  
  18.   struct test test_example;  
  19.   printf("sizeof test is %d\n"sizeof(test_example));  
  20.   printf("address of test_example is %p\n", &test_example);  
  21.   printf("address of test_example according to 'array' %p\n", container_of(test_example.array, struct test, array));   
  22.   printf("address of test_example according to 'pointer' %p\n", container_of(&test_example.pointer, struct test, pointer));  
  23.   return 0;  
  24. }  

编译、执行,输出的结果如下图所示:

不用我多说了吧,container_of的作用在于,给定某结构体中字段的地址,能够获取该结构体的起始地址。

相关内容