Linux内核开发:container_of分析

2. 举例来说明container_of的使用
1>正确示例:
#include <stdio.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 f1;
  };
 int main(void)
  {
          struct test_struct *test_struct;
          struct test_struct init_struct ={12,'a',12.3};
          char *ptr_ch = &init_struct.ch;
          test_struct = container_of(ptr_ch,struct test_struct,ch);
          printf("test_struct->num =%d\n",test_struct->num);
          printf("test_struct->ch =%c\n",test_struct->ch);
          printf("test_struct->ch =%f\n",test_struct->f1);
          return 0;
  }
执行结果:
jibo@jibo-VirtualBox:~/cv_work/work/list/container_of $ ./main
test_struct->num =12
test_struct->ch =a
test_struct->ch =12.300000

2>错误示例:
  #include <stdio.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 f1;
  };
  int main(void)
  {
          struct test_struct *test_struct;
          char real_ch = 'A';
          char *ptr_ch = &real_ch;
          test_struct = container_of(ptr_ch,struct test_struct,ch);
          printf("test_struct->num =%d\n",test_struct->num);
          printf("test_struct->ch =%c\n",test_struct->ch);
          printf("test_struct->ch =%f\n",test_struct->f1);
          return 0;
  }
执行结果为:
jibo@jibo-VirtualBox:~/cv_work/work/list/container_of1 $ ./main
test_struct->num =0
test_struct->ch =A
test_struct->ch =0.000000
注意,由于这里并没有使用一个具体的结构体变量,所以成员num和f1的值是不确定的。

相关推荐