Linux内核实现List二个关键的宏offsetof 和 container_of
2015-06-09 15:27
751 查看
二个宏定义在inux/kernel.h头文件
关键之处在于将地址0强制转换为type类型的指针,从而定位到member在结构体中偏移位置。编译器认为0是一个有效的地址,从而认为0是type指针的起始地址。
container_of宏分为两部分,
1.const typeof( ((type *)0)->member ) *__mptr = (ptr);
通过typeof定义一个member指针类型的指针变量__mptr,(即__mptr是指向member类型的指针),并将__mptr赋值为ptr,关键之处将_mptr转换为member类型的指针。
2: (type )( (char )__mptr - offsetof(type,member) ),通过offsetof宏计算出member在type中的偏移,然后用member的实际地址__mptr减去偏移,得到type的起始地址,即指向type类型的指针。
1.offsetof
offsetof宏的定义如下:#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
关键之处在于将地址0强制转换为type类型的指针,从而定位到member在结构体中偏移位置。编译器认为0是一个有效的地址,从而认为0是type指针的起始地址。
2.container_of
container_of宏定义如下:#define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );})
container_of宏分为两部分,
1.const typeof( ((type *)0)->member ) *__mptr = (ptr);
通过typeof定义一个member指针类型的指针变量__mptr,(即__mptr是指向member类型的指针),并将__mptr赋值为ptr,关键之处将_mptr转换为member类型的指针。
2: (type )( (char )__mptr - offsetof(type,member) ),通过offsetof宏计算出member在type中的偏移,然后用member的实际地址__mptr减去偏移,得到type的起始地址,即指向type类型的指针。
相关文章推荐
- 嵌入式Linux常见问题
- Linux下交互式添加用户脚本(四个示例)
- 配置Centos服务器
- (转)Linux进程池的实现
- linux基本命令<2>
- Linux C编程从入门到精通——Linux基础
- Unix/Linux的 mmap()内存映射
- CentOS6.5安装配置Samba
- linux内核源码的技巧
- Android或Linux调试addr2line工具锁定命令的使用
- at91sam9260ek的板级、irq初始化-小试牛刀
- linux下jdk配置
- centos下postgres源码编译
- linux 的date命令及系统时间设置
- ZH奶酪:Linux/Ubuntu 安装/卸载 软件
- linux下安装jboss6+jdk1.7
- vnc viewer for linux
- Linux中的AIO(异步I/O asynchronous I/O )
- linux运行run文件显示cannot execute binary file
- Linux命令find -perm使用方法