设为首页 加入收藏

TOP

contain_of宏定义
2018-10-21 18:11:12 】 浏览:70
Tags: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 =%d\n",test_struct->num);
18           printf("test_struct->ch =%c\n",test_struct->ch);
19           printf("test_struct->ch =%f\n",test_struct->f1);
20           return 0;
21   }

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇集合实例(集合覆盖) 下一篇C语言第七次博客作业--一二维数组

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目