博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
container_of()宏
阅读量:4047 次
发布时间:2019-05-25

本文共 1640 字,大约阅读时间需要 5 分钟。

指针ptr指向结构体type中的成员member;通过指针ptr,返回结构体type的起始地址
          type
      |----------|
      |          |
      |          |
      |----------|
ptr-->| member --|
      |----------|
      |          |
      |          |
      |----------|
/**
* 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) );})
--------------------------------------------------
d = usb_device->dev.driver
container_of(d, struct usb_device_driver, drvwrap.driver)
     struct usb_device
|----------------------------|
|                            |
|                            |
|----------------------------|
|                            | struct device
|struct device_driver *driver|--+
|                            | -|
|----------------------------|
-
|
|                            |
-
|
|                            |
-
|
|----------------------------|
-
|
                                |
+-------------------------------+
|
|    struct usb_device_driver
|
--
|---------------------------|
|
--
|                           |
|
--
|                           |
|
--
|---------------------------|
+-->|struct device_driver driver| struct usbdrv_wrap drvwrap
    |int             for_devices|
    |---------------------------|
    |                           |
    |---------------------------|

 

 

--------------------------------------------
container_of宏,它的功能是得到包含某个结构成员的结构的指针:
 
其实现如下:
 
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({                      /
        const typeof( ((type *)0)->member ) *__mptr = (ptr);    /
        (type *)( (char *)__mptr - offsetof(type,member) );})
 
    分析可知__mptr指向的是一个type结构里typeof(((type *)0)->member)类型member成员的指针,offsetof(type,member)是这个成员在结构中的偏移,单位是字节,所以为了计算type结构的起始地址,__mptr减去它自己的偏移。
 

转载地址:http://jakci.baihongyu.com/

你可能感兴趣的文章
TaskScheduler 是什么?有什么作用?
查看>>
一篇文章搞懂 DAGScheduler 的调度流程
查看>>
SparkEnv 是什么?有什么作用?
查看>>
SparkConf 是什么?有什么作用?
查看>>
SecurityManager 是什么?有什么作用?
查看>>
如何理解 Java 的线程中断机制?
查看>>
线程的挂起(suspend)和继续执行(resume)是什么情况?
查看>>
线程的等待线程结束(join)和谦让(yield)是什么情况?
查看>>
finalize 真的一点用没有吗?
查看>>
关于HDU 1713 相遇周期
查看>>
BF算法
查看>>
poj 1068 Parencodings 大模拟 水题 暑假第7题
查看>>
poj 2996 Help Me with the Game 暑假第10题 模拟 大水
查看>>
hdu 1937 Finding Seats 尺取法
查看>>
hdu 1941 Justice League 无向完全图
查看>>
hdu 1285 确定比赛名次 拓扑排序模板题 优先队列
查看>>
poj 1797 Heavy Transportation 最小生成树 最大生成树
查看>>
hdu 1102 Constructing Roads 最小生成树Kruskal
查看>>
hdu 2489 Minimal Ratio Tree 最小生成树kruskal
查看>>
hdu 3790 最短路径问题 最短路Dijkstra
查看>>