首頁  >  文章  >  運維  >  Linux核心基礎篇——container_of原理與實際應用

Linux核心基礎篇——container_of原理與實際應用

嵌入式Linux充电站
嵌入式Linux充电站轉載
2023-07-31 15:46:13950瀏覽

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的關係:

Linux核心基礎篇——container_of原理與實際應用
  • 原理簡述:

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

以上是Linux核心基礎篇——container_of原理與實際應用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:嵌入式Linux充电站。如有侵權,請聯絡admin@php.cn刪除