contain_of宏定义

时间:2022-05-03
本文章向大家介绍contain_of宏定义,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

实现方式:

  container_of(ptr, type, member) ;

   其实它的语法很简单,只是一些指针的灵活应用,它分两步:

    第一步,首先定义一个临时的数据类型(通过typeof( ((type *)0)->member )获得)与ptr相同的指针变量__mptr,然后用它来保存ptr的值。

    第二步,用(char *)__mptr减去member在结构体中的偏移量,得到的值就是整个结构体变量的首地址(整个宏的返回值就是这个首地址)。

    其中的语法难点就是如何得出成员相对结构体的偏移量?

通过例子说明,如清单1:

 1 #include <stdio.h>
 2 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
 3 #define  container_of(ptr, type, member) ({                      
 4                       const typeof( ((type *)0)->member ) *__mptr = (ptr);    
 5                        (type *)( (char *)__mptr - offsetof(type,member) );})
 6 struct test_struct {
 7            int num;
 8           char ch;
 9           float f1;
10   };
11  int main(void)
12   {
13           struct test_struct *test_struct;
14           struct test_struct init_struct ={12,'a',12.3};
15           char *ptr_ch = &init_struct.ch;
16           test_struct = container_of(ptr_ch,struct test_struct,ch);
17           printf("test_struct->num =%dn",test_struct->num);
18           printf("test_struct->ch =%cn",test_struct->ch);
19           printf("test_struct->ch =%fn",test_struct->f1);
20           return 0;
21   }