核心中的container of的實現

2021-06-01 13:34:57 字數 1270 閱讀 4765

1、         功能

container_of是從乙個已知的結構體和其中乙個成員及其該成員的指標,返回該結構體的首位址。字面意思:裝某某成員的容器的位址。

2、        原型(在linux/kernel.h中定義)

#definecontainer_of(ptr, type, member) ()

ptr就是成員的指標,type是結構體型別,member是結構體成員。其中的offsetof又是乙個巨集定義,在linux/stddef.h中定義:

#define offsetof(type, member) ((size_t) &((type*)0)->member)

offsetof(offset偏移量,意思某某成員在該結構體的偏移量)是為了求結構體中某個成員相對於結構體首位址的偏移量,但現在不知道其首位址,所以用了乙個技巧,相當於把結構體移到位址0,這樣取出該成員的位址就是相對於結構體首位址的偏移量。這兒有乙個注意點,就是在0位址取結構體的成員的位址,這是允許的,因為我們沒有取該位址裡的值,而是取該位址。(事實上,此處並沒有值,所以取值會出現段錯誤)。另外__mptr指標需轉換成char*型,因為指標減去乙個數相當於減去該指標型別的那麼多個偏移量。

3、        **驗證如下:

#include #include struct stu;

int main(void)

; printf("offset of age is [%d]\n", offsetof(struct stu, age));

printf("offset of score is [%d]\n", offsetof(struct stu, score));

printf("%d\n", (size_t)((int)&xiaoyuan.age - (int)&xiaoyuan));

printf("%d\n", (size_t)&(((struct stu*)0)->age) );

/* 相當於

* printf("%d\n", (size_t)(&(((struct stu*)0)->age)- 0) );

*/return 0;

}

執行結果:

[root@localhost~]# ./a.out

offset of age is[20]

offset of scoreis [24]

2020

linux核心中container of詳解

在linux 核心中,container of 函式使用非常廣,例如 linux核心鍊錶 list head 工作佇列work struct中。在linux 核心中有乙個大名鼎鼎的巨集container of 這個巨集是用來幹嘛的呢?我們先來看看它在核心中是怎樣定義的。呵呵,乍一看不知道是什麼東東。...

Linux 核心巨集 container of

container of ptr,type,member arguments ptrthe pointer to the member.代表指標 type the type ofthe container struct this isembedded in.型別 member 成員變數 the na...

核心 巨集定義 container of

container of 1.1 container of介紹 定義 container of在linux核心的include linux kernel.h中定義。define container of ptr,type,member 說明 根據 結構體 type 變數 中的 域成員變數 membe...