container_of的使用

来源:互联网 发布:和禹网络培训费 编辑:程序博客网 时间:2024/06/02 16:10

contanier_of是Linux内核中常用的宏,用于从包含在某个结构中的指针获得结构本身的指针,通俗地讲就是通过结构体变量中某个成员的首地址进而获得整个结构体的地址

正确的使用如下:

#include <stdio.h>#include <string.h>#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)#define container_of(ptr, type, member) ({      \    const typeof( ((type *)0)->member ) *__mptr = (ptr); \    (type *)( (char *)__mptr - offsetof(type,member) );})  struct test_struct {      int num;      char ch;      float fl;  };    int main(void)  {      struct test_struct init_test_struct = { 99, 'C', 59.12 };        char *char_ptr = &init_test_struct.ch;        struct test_struct *test_struct = container_of(char_ptr, struct test_struct, ch);            printf(" test_struct->num = %d\n test_struct->ch = %c\n test_struct->fl = %f\n",           test_struct->num, test_struct->ch, test_struct->fl);            return 0;  }  



参考:http://blog.csdn.net/npy_lp/article/details/7010752

0 0