Chinaunix首页 | 论坛 | 博客
  • 博客访问: 103595
  • 博文数量: 39
  • 博客积分: 2000
  • 博客等级: 大尉
  • 技术积分: 318
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-09 10:01
文章分类

全部博文(39)

文章存档

2011年(7)

2010年(20)

2009年(12)

我的朋友

分类: LINUX

2009-10-29 14:24:31

转载自:http://blog.chinaunix.net/u1/58968/showart_461749.html
container_of()宏


指针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减去它自己的偏移。
 
阅读(312) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~