Linux内核Container_of宏解析
来源:互联网 发布:php curl 编码 编辑:程序博客网 时间:2024/05/17 20:28
Container_of是Linux内核中一个很常用的宏,其作用为:用结构体成员指针获得结构变量本身的指针。这里来分析一下它的实现。
type:表示结构体类型
member:表示结构体中的成员
这个中间变量的命名规则:
"__"代表内部使用,内核编程中常常这么做;
如有疑问,欢迎留言探讨。
首先,该宏定义在Linux 内核 include/linux/kernel.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) );})
ptr:表示结构体中member的地址type:表示结构体类型
member:表示结构体中的成员
根据前面所述,就是通过ptr的地址可以返回type类型的结构体变量首地址。其实它的实现很简单,都是对C指针的灵活应用。
const typeof( ((type *)0)->member ) *__mptr = (ptr);
定义一个中间变量__mptr,指向某个成员的指针ptr。这个中间变量的命名规则:
"__"代表内部使用,内核编程中常常这么做;
“m"代表middle。
(type *)( (char *)__mptr - offsetof(type,member) );
通过中间变量__mptr(指向某个成员的指针)减去这个成员结构体中的偏移来得到结构体的指针。其中偏移的获取offsetof宏的实现:
#ifdef __compiler_offsetof #define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER) #else #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) #endif
如有疑问,欢迎留言探讨。
0 0
- linux内核container_of宏解析
- Linux内核Container_of宏解析
- 深入浅出实例解析linux内核container_of宏
- Linux内核container_of宏
- Linux内核,container_of 宏
- linux 内核中container_of和offsetof宏定义解析
- linux内核中的container_of宏
- Linux内核中的container_of宏
- Linux内核:container_of宏分析
- Linux内核中的常用宏--container_of(container_of(ptr, type, member)
- 【转】Linux内核的container_of宏
- 对linux内核宏container_of的理解
- Linux内核中container_of宏的理解
- 对linux内核宏container_of的理解
- Linux内核中container_of宏的理解
- linux内核container_of宏定义分析
- linux内核的container_of()宏定义分析
- Linux内核中container_of宏的理解
- 广度优先遍历
- 【POJ 2728】[01分数规划]Desert King
- springmvc和mybatis整合 之 一、需求分析
- 配置opencv步骤
- namespace
- Linux内核Container_of宏解析
- 我的Java之旅 第五课 JAVA 语言语法 集合
- 用递归算法写一段程序实现 1+2+...+1000000 、java.lang.StackOverflowError 异常,原因,bug调查,处理
- java int与integer的区别
- sublime自动刷新网页
- spring中配置hibernateTemplate
- MAC系统下安装mongodb 配合nodeJS简单使用mongodb
- 程序员如何包装自己
- 软工文档总结