公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(50元/站),

点击这里在线咨询客服
新站提交
  • 网站:51998
  • 待审:31
  • 小程序:12
  • 文章:1030137
  • 会员:747

Linux内核中经常可见container_of的身影,它在实际驱动的编写中也是广泛应用。

container_of原理

作用:通过结构体的某个成员变量地址找到该结构体的首地址。

定义如下:

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

登录后复制

    ptr:结构体成员变量的指针
    type:结构体类型
    member:结构体成员变量的名字

    换句话说,叫:已知结构体type的成员member的地址ptr,求解结构体type的起始地址。

    计算公式为:type的起始地址 = ptr –size (size为member的大小)

    以一幅图说明ptr、type、member的关系:

      原理简述:

      container_of的妙处就在于以0作为成员变量member的基址。

      其中定义了一个中间变量__mptr,"__"代表内部使用,“m”代表middle。

      #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

      登录后复制

      typeof( ((type *)0)->member )是获取member的类型,__mptr = (ptr)判断ptr与member是否为同一类型,offsetof计算成员member的大小size。

      驱动中的实际例子

      例如内核的pwm驱动,通过成员变量chip,找到结构体bcm2835_pwm:

      struct bcm2835_pwm {
       struct pwm_chip chip;
       struct device *dev;
       void __iomem *base;
       struct clk *clk;
      };
      
      static inline struct bcm2835_pwm *to_bcm2835_pwm(struct pwm_chip *chip_ptr)
      {
       return container_of(chip_ptr, struct bcm2835_pwm, chip);
      }

      登录后复制

      使用container_of通常都会定义一个函数,并且命名为to_xxx或者to_find_xxx,代表要找xxx这个结构体,传参则传入成员变量指针,另外函数也会声明为inline。

以上就是Linux内核基础篇——container_of原理和实际应用的详细内容,更多请关注www.92cms.cn其它相关文章!

分享到:
标签:Linux 内核 原理 基础 实际应用
用户无头像

网友整理

注册时间:

网站:5 个   小程序:0 个  文章:12 篇

  • 51998

    网站

  • 12

    小程序

  • 1030137

    文章

  • 747

    会员

赶快注册账号,推广您的网站吧!
最新入驻小程序

数独大挑战2018-06-03

数独一种数学游戏,玩家需要根据9

答题星2018-06-03

您可以通过答题星轻松地创建试卷

全阶人生考试2018-06-03

各种考试题,题库,初中,高中,大学四六

运动步数有氧达人2018-06-03

记录运动步数,积累氧气值。还可偷

每日养生app2018-06-03

每日养生,天天健康

体育训练成绩评定2018-06-03

通用课目体育训练成绩评定