container_of函数原理分析
来源:互联网 发布:在线编程 编辑:程序博客网 时间:2024/04/29 06:07
/**
* container_of - cast a member of a structureout 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.//成员变量名
*
*/
#definecontainer_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member )*__mptr = (ptr); \
(type *)( (char *)__mptr -offsetof(type,member) );})
每行前面的数字是所在的行数。 可见在这个宏定义中用到了另外两个宏:typeof 和 offsetof 。
对 typeof 的理解:
实际上, typeof 并不是宏定义,它是GCC的关键字,是GCC特有的特性。如果只知道一个变量的名字要得到其类型,并不是宏定义能够完成的,这需要编译时的信息。所 以,typeof 操作是GCC内置的功能,在内核头文件和Glibc头文件中都是找不到typeof的宏定义的。
对 offsetof 的理解:
offsetof 是一个真正的宏,它定义在内核源代码 include/linux/stddef.h 文件中:
第一步得到成员member相对于结构体起始位置的偏移量(就是说相对于结构体的首地址来说往后此成员变量往后偏移了几个字节)
24 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
在这里,TYPE表示一个结构体的类型,MEMBER是结构体中的一个成员变量的名字。offsetof 宏的作用是计算成员变量 MEMBER 相对于结构体起始位置的内存偏移量,以字节(Byte)为单位。
它的计算原理是,把整数0进行强制类型转换,转换为一个 TYPE 类型的指针; 然后找到成员变量 MEMBER; 最后用取地址符 “&” 得到 MEMBER 的地址。 因为结构体是从地址0处开始的,所以 MEMBER 的地址就是其相对于结构体起始位置的偏移量。第一步完成
第二步:减法操作
对 container_of 的理解:
三个参数, ptr是成员变量的指针, type是指结构体的类型, member是成员变量的名字。 container_of 的作用就是在已知某一个成员变量的名字、指针和结构体类型的情况下,计算结构体的指针,也就是计算结构体的起始地址。 计算的方法其实很简单,就是用该成员变量的指针减去它相对于结构体起始位置的偏移量。
493 #define container_of(ptr, type, member) ({ \
494 const typeof( ((type *)0)->member ) *__mptr = (ptr); \//成员指针赋值
495 (type *)( (char *)__mptr - offsetof(type,member) );})//减操作
在这个定义中,typeof( ((type *)0)->member ) 就是获得 member 的类型, 然后定义了一个临时的常量指针 __mptr, 指向 member 变量。 为什么不直接使用 ptr 而要多此一举呢? 我想可能是为了避免对 ptr 及prt 指向的内容造成破坏。 把 __mptr 转换成 char * 类型, 因为 offsetof 得到的偏移量是以字节为单位。两者相减得到结构体的起始位置, 再强制转换成 type 类型。
- container_of函数原理分析
- container_of函数原理分析
- container_of分析
- container_of 分析
- container_of分析
- container_of分析
- container_of分析
- container_of分析
- container_of分析
- container_of分析
- container_of分析
- container_of分析
- container_of分析
- container_of分析
- container_of分析
- container_of分析
- container_of分析
- container_of分析
- JDBC之PreparedStatement
- 四种通信方式区别
- jvm 调优总结
- Tez在hadoop 2.2.0下的安装部署测试
- Spring缓存 org.springframework.cache.ehcache.EhCacheManagerFactoryBean
- container_of函数原理分析
- 线性表顺序存储结构的优缺点
- swing制作socket例子
- MAC安装python的mysqldb包
- Win32ASM使用List-View控件的问题
- WIN7 RC 系统服务函数变更
- 信号
- svn问题
- Python 字符编码转换要诀