对container_of(ptr,type,member)分析
来源:互联网 发布:房地产大数据 走势 编辑:程序博客网 时间:2024/06/03 20:37
对container_of(ptr,type,member)
#define container_of(ptr, type, member) ({ \
const typeof(((type*)0)->member) *__mptr= (ptr); \
(type *)((char*)__mptr- offsetof(type,member));})
#defineoffsetof(TYPE, MEMBER)((size_t)&((TYPE*)0)->MEMBER)
const typeof(((type*)0)->member) *__mptr= (ptr); \
(type *)((char*)__mptr- offsetof(type,member));})
#defineoffsetof(TYPE, MEMBER)((size_t)&((TYPE*)0)->MEMBER)
它的作用是:设ptr是某个type类型结构中的member成员变量的地址,该宏的结果是得到该type的地址。即有结构中成员变量的地址得到结构的地址。
1.ptr为物理地址,其类型和member类型一致,最终使用typeof(((type*)0)->member)
由编译器自动返回member的类型
2.type为包含member成员的结构体
3.offsetof(type,member)为member成员在type结构体中的偏移值,大小范围0~sizeof(type)字节
(因为以0地址为type类型数据结构的起始地址)
4.ptr-offsetof()就等于包含该ptr的type结构体父变量的物理起始地址,强制转换为(type*).
5.
由编译器自动返回member的类型
2.type为包含member成员的结构体
3.offsetof(type,member)为member成员在type结构体中的偏移值,大小范围0~sizeof(type)字节
(因为以0地址为type类型数据结构的起始地址)
4.ptr-offsetof()就等于包含该ptr的type结构体父变量的物理起始地址,强制转换为(type*).
5.
((size_t)&((TYPE*)0)->MEMBER)表示当结构TYPE为0时其成员MEMBER的地址,即位移量。
另一种解释:
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
关于typeof,这是gcc的C语言扩展保留字,用于声明变量类型.
const typeof( ((type *)0->member ) *__mptr = (ptr);意思是声明一个与member同一个类型的指针常量 *__mptr,并初始化为ptr.
(type *)( (char *)__mptr - offsetof(type,member) );意思是__mptr的地址减去member在该struct中的偏移量得到的地址, 再转换成type型指针. 该指针就是member的入口地址了.
#ifdef __compiler_offsetof
#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
#else
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif
(TYPE *)0将地址0强制转换为结构体,MEMBER是该struct中的一个成员. 由于该struct的基地址为0, MEMBER的地址就是该成员相对与struct头地址的偏移量.
- 对container_of(ptr,type,member)分析
- 对container_of(ptr,type,member)分析
- 对container_of(ptr,type,member)分析
- container_of(ptr, type, member)
- container_of(ptr, type, member)
- container_of(ptr, type, member)
- container_of(ptr, type, member)
- container_of(ptr, type, member)
- container_of(ptr, type, member)
- container_of(ptr, type, member)
- 浅析container_of(ptr, type, member)
- 浅析container_of(ptr, type, member)
- 浅析container_of(ptr, type, member)
- 浅析container_of(ptr, type, member)
- 浅析container_of(ptr, type, member)
- 浅析container_of(ptr, type, member)
- 浅析container_of(ptr, type, member)
- 浅析container_of(ptr, type, member)
- 浅谈Oracle VM VirtualBox虚拟机的网络配置
- ollydbg和IDA,HIEW的简单结合
- C++标准库find简单用法
- my english document for threadx
- .NET 泛型
- 对container_of(ptr,type,member)分析
- 如何成为一名黑客
- Linux学习-账户相关命令
- ???
- onvif开发:使用wsdl2h和soap2cpp生成开发文件
- 探索并发编程(三)------Java存储模型和共享对象
- 为什么说在持有自旋锁时不能进入睡眠或阻塞
- Linux(CentOS 6.2)系统上安装Mplayer播放器
- GDB中应该知道的几个调试方法