免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 612 | 回复: 0
打印 上一主题 下一主题

container_of()宏 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-01-11 16:33 |只看该作者 |倒序浏览
指针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减去它自己的偏移。



本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/58968/showart_461749.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP