container_of与offsetof详解
来源:互联网 发布:temp编程 编辑:程序博客网 时间:2024/06/05 03:24
Linxu内核中宏container_of的作用是根据结构体成员的一个指针地址来获取整个结构体的地址,要想理解container_of,我们先来看看宏offsetof
我们先来看看宏offsetof
在Linux内核中是这样定义的:#ifndef _LINUX_STDDEF_H
#define _LINUX_STDDEF_H
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif
一共4步
1. ( (TYPE *)0 ) 将零转型为TYPE类型指针;
2. ((TYPE *)0)->MEMBER 访问结构中的数据成员;
3. &( ( (TYPE *)0 )->MEMBER )取出数据成员的地址;
4.(size_t)(&(((TYPE*)0)->MEMBER))结果转换类型。巧妙之处在于将0转换成(TYPE*),结构以内存空间首地址0作为起始地址,则成员地址自然为偏移地址;
一共4步
1. ( (TYPE *)0 ) 将零转型为TYPE类型指针;
2. ((TYPE *)0)->MEMBER 访问结构中的数据成员;
3. &( ( (TYPE *)0 )->MEMBER )取出数据成员的地址;
4.(size_t)(&(((TYPE*)0)->MEMBER))结果转换类型。巧妙之处在于将0转换成(TYPE*),结构以内存空间首地址0作为起始地址,则成员地址自然为偏移地址;
再来看看宏container_of
在Linux内核中是这样定义的:
#ifndef _LINUX_KERNEL_H
#define _LINUX_KERNEL_H
#include "stddef.h"
/**
* container_of - cast a member of a structure out to the containing structure
* @ptr: the pointer to the member.
* @type: the type of the container struct this is embedded in.
* @member: the name of the member within the struct.
*
*/
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
#endif
其中,typeof是GNU C对标准C的扩展,它的作用是根据变量获取变量的类型。因此,上述代码中的第2行的作用是首先使用typeof获取结构体域变量member的类型为 type,然后定义了一个type指针类型的临时变量__mptr,并将实际结构体变量中的域变量的指针ptr的值赋给临时变量__mptr
其中,typeof是GNU C对标准C的扩展,它的作用是根据变量获取变量的类型。因此,上述代码中的第2行的作用是首先使用typeof获取结构体域变量member的类型为 type,然后定义了一个type指针类型的临时变量__mptr,并将实际结构体变量中的域变量的指针ptr的值赋给临时变量__mptr
第三行代码分为三步:
1.(char *)__mptr转换为字节型指针。
2.(char *)__mptr - offsetof(type,member) )用来求出结构体起始地址(为char *型指针),
3.然后(type *)( (char *)__mptr - offsetof(type,member) )在(type *)作用下进行将字节型的结构体起始指针转换为type *型的结构体起始指针。
1 0
- container_of与offsetof详解
- container_of,offsetof,与typeof
- offsetof与container_of宏
- offsetof与container_of宏
- offsetof与container_of
- container_of 和 offsetof 宏详解
- container_of与offsetof的原理
- offsetof与container_of宏[总结]
- [转载]offsetof与container_of宏
- offsetof与container_of宏[总结]
- offsetof与container_of宏[总结]
- offsetof与container_of宏[总结]
- offsetof与container_of宏[总结]
- offsetof与container_of宏[总结]
- offsetof与container_of宏[总结]
- Offsetof与container_of宏总结
- offsetof与container_of宏[总结]
- offsetof宏与container_of宏
- 关于标准输出重定向到 管道的使用
- fmt格式转化date格式
- poj2312
- 私有云的3个优势
- ubuntu 16.04 搭建vsftp
- container_of与offsetof详解
- intergrate sparkSQL with hive
- jquery 更新数据的通过样式回显功能
- Android架构之组件化方案
- 纸牌博弈问题
- 执行shell传参多出两个进程号
- Vulkan编程指南翻译 第七章 图形管线 第4节 创建简单的图形管线
- 北邮OJ-94. 最小距离查询-13计院上机D
- java的一些其他情况(1):System.getProperty()