container_of

来源:互联网 发布:数据复制 编辑:程序博客网 时间:2024/05/18 01:26

内核中的container_of

内核源码(X.Y.Z/inlcude/linux/kernel.h):

/**
 * 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) );})


  • container_of 这个宏的功能是通过一个结构变量中一个成员的地址找到这个结构体变量的首地址。

container_of(ptr,type,member) 

    ptr:指向已知成员指针

    type:要查找的结构类型

    member:已知成员名字

  • const typeof(((type *)0)->member)* __mptr = (ptr);

typeof是GNU C对标准C的扩展,它的作用是根据变量获取变量的类型。type是某struct的类型 0是一个假想TYPE类型struct,member是该struct中的一个成员. 由于该struct的基地址为0, member的地址就是该成员相对与struct头地址的偏移量.

(type *)( (char *)__mptr - offsetof(type,member) );意思是__mptr的地址减去member在该struct中的偏移量得到的地址, 再转换成type型指针. 该指针就是member的入口地址了.


0 0
原创粉丝点击