内核之container_of的理解
来源:互联网 发布:南京图书销售软件 编辑:程序博客网 时间:2024/05/16 17:50
最近在公司用户态看到有些地方使用了container_of,之前遇到过但都作为一个功能函数使用,没有仔细研究过,最近就抽出点时间来专门看了下这个函数。
这个函数还是蛮有意思的:
/*
* 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 - ((size_t) &((type*)0)->member) );})
简单的理解一下这个container_of宏函数:
第一句:首先定义了一个__mptr的指针,这个指针的类型是typeof( ((type *)0)->member ),这个指针里存放的数据是ptr的值,ptr是什么呢,ptr是type结构体中member成员的地址指针。
第二句:(size_t) &((type *)0)->member这个的意思是将0地址强转为type *类型,然后对member成员取地址,那么现在我们可以想到,对于一个以0地址为头指针的结构体,member成员的地址即为头指针和member间的相对偏移。最后用__mptr减去这个相对偏移即可以得到结构体type的头指针。
现在一起探讨一个问题,为什么要定义一个__mptr来存储ptr的值,我们完全可以用下面的宏:
#define container_of(ptr, type, member)({\
(type *)((char *)(ptr) - ((size_t)&((type *)0->member)));})
效果也是一样的嘛,希望知道原因的高手不吝赐教。。。
- 内核之container_of的理解
- 对linux内核宏container_of的理解
- Linux内核中container_of宏的理解
- 对linux内核宏container_of的理解
- Linux内核中container_of宏的理解
- Linux内核中container_of宏的理解
- 内核宏定义container_of的理解
- linux内核中container_of的理解
- 关于linux内核container_of宏的理解
- 对linux内核的container_of和offsetof宏的理解
- uclinux内核的container_of
- 对container_of的理解
- 对container_of的理解
- container_of的理解
- container_of的理解
- container_of的理解
- 内核中的container_of的实现
- Linux内核的Container_of机制
- MFC中修改CStatic控件颜色
- Ubuntu下搭建Opencv2.4.8
- SOAP协议服务端编写(Axis2 XFire)
- 运行django的manage.py runserver 8000时提示errno 10013的解决方法
- STM32芯片片内FLASH模拟EEPROM实验
- 内核之container_of的理解
- 使用自己的jdbc类,使用spring的事务管理.自己的类里面不依赖spring框架.
- 算数运算符
- Java 对象及其引用
- ListActivity & ExpandableListActivity
- 第十三周上机实践项目——点、圆的关系
- HW的最后一轮面试
- Mac OS X 10.9 XCode5.1 Run Crash运行就崩溃,试试用5.1.1
- STM32串口IAP实验