zoukankan      html  css  js  c++  java
  • container_of深入理解

    container_of在linux头文件kernel.h中定义,如下:

      14#ifndef offsetof
      15#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
      16#endif
      17
      18#ifndef container_of
      19/**
      20 * container_of - cast a member of a structure out to the containing structure
      21 * @ptr:        the pointer to the member.
      22 * @type:       the type of the container struct this is embedded in.
      23 * @member:     the name of the member within the struct.
      24 *
      25 */
      26#define container_of(ptr, type, member) ({                      /
      27        const typeof(((type *)0)->member) * __mptr = (ptr);     /
      28        (type *)((char *)__mptr - offsetof(type, member)); })
      29#endif
    这里在简单插入对typeof的理解:
    typeof关键字是C语言中的一个新扩展。从语义上看,typeof 关键字将用做类型名(typedef名称)并指定类型。
    请注意,typeof构造中的类型名不能包含存储类说明符,如externstatic。不过允许包含类型限定符,如constvolatile
    例如:

      1. struct demo_struct {
       2.     type1 member1;
       3.     type2 member2;
       4.     type3 member3;
       5.     type4 member4;
       6. };
       7.
       8. struct demo_struct demo;

       struct demo_struct *demop = container_of(memp, struct demo_struct, member3);
    首先,我们将container_of(memp, struct demo_struct, type3)根据宏的定义进行展开如下:
       1. struct demo_struct *demop = ({                      /
       2.     const typeof( ((struct demo_struct *)0)->member3 ) *__mptr = (memp);    /
       3.     (struct demo_struct *)( (char *)__mptr - offsetof(struct demo_struct, member3) );})

    假设结构体变量demo在实际内存中的位置如下图所示:
         demo
    +-------------+ 0xA000
    |   member1              |
    +-------------+ 0xA004
    |   member2             |
    |                                |
    +-------------+ 0xA010
    |   member3             |
    |                                |
    +-------------+ 0xA018
    |   member4             |
    +-------------+
    则,在执行了上述代码的第2行之后__mptr的值即为0xA010。

    同样,我们将上述的offsetof调用展开,即为:
       3. (struct demo_struct *)( (char *)__mptr - ((size_t) &((struct demo_struct *)0)->member3) );
    可见,offsetof的实现原理就是取结构体中的域成员相对于地址0的偏移地址,也就是域成员变量相对于结构体变量首地址的偏移。
    因此,offsetof(struct demo_struct, member3)调用返回的值就是member3相对于demo变量的偏移。结合上述给出的变量地址分布图可知,offsetof(struct demo_struct, member3)将返回0x10。
    于是,由上述分析可知,此时,__mptr==0xA010,offsetof(struct demo_struct, member3)==0x10。
    因此, (char *)__mptr - ((size_t) &((struct demo_struct *)0)->member3) == 0xA010 - 0x10 == 0xA000,也就是结构体变量demo的首地址(如上图所示)。

  • 相关阅读:
    雪妖现世:给SAP Fiori Launchpad增添雪花纷飞的效果
    ABAP开发环境语法高亮的那些事儿
    如何使用Prometheus采集SAP ABAP Netweaver的应用日志数据
    如何免费试用SAP的Fiori应用
    使用ABAP绘制可伸缩矢量图
    背景建模
    C# 属性和索引
    Equation
    Phone numbers
    BerOS file system
  • 原文地址:https://www.cnblogs.com/p2liu/p/6048784.html
Copyright © 2011-2022 走看看