Linux内核中container_of原理详解

嵌入式技术

1344人已加入

描述

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的大小)

以一幅图说明ptrtypemember的关系:

指针

  • 原理简述:

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

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

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

typeof( ((type *)0)->member )是获取member的类型,__mptr = (ptr)判断ptrmember是否为同一类型,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

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分