1> container_of 是 Linux 內核中極常用的巨集,作用是「從某個已知成員的指標,取得包含它的結構體本身的指標」。白話來說,就是透過結構體中某個成員的位址,回推整個結構體的起始位址。
2> 介面:
container_of(ptr, type, member)
ptr:結構體中 member 的位址;type:結構體型別;member:結構體中的成員名。透過 ptr 即可回傳結構體的首位址。
3> 實作:
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type, member) ); })
語法其實很單純,只是指標的靈活應用,分兩步:
第一步,用 typeof(((type *)0)->member) 取得成員的型別,宣告一個同型別的指標 __mptr 並保存 ptr。typeof 是 GNU C 對標準 C 的擴充,能依運算式推導型別,在內核中隨處可見。
第二步,用 (char *)__mptr 減去 member 在結構中的偏移量(offsetof),得到的就是整個結構體的首位址,也就是這個巨集的回傳值。
#include <stdio.h>
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type, member) ); })
struct test_struct {
int num;
char ch;
float f1;
};
int main(void)
{
struct test_struct *test_struct;
struct test_struct init_struct = {12, 'a', 12.3};
char *ptr_ch = &init_struct.ch;
test_struct = container_of(ptr_ch, struct test_struct, ch);
printf("test_struct->num = %d\n", test_struct->num);
printf("test_struct->ch = %c\n", test_struct->ch);
printf("test_struct->f1 = %f\n", test_struct->f1);
return 0;
}
執行結果:
test_struct->num = 12 test_struct->ch = a test_struct->f1 = 12.300000
int main(void)
{
struct test_struct *test_struct;
char real_ch = 'A';
char *ptr_ch = &real_ch; // 指向一個獨立的 char 變數
test_struct = container_of(ptr_ch, struct test_struct, ch);
printf("test_struct->num = %d\n", test_struct->num);
printf("test_struct->ch = %c\n", test_struct->ch);
printf("test_struct->f1 = %f\n", test_struct->f1);
return 0;
}
執行結果:
test_struct->num = 0 test_struct->ch = A test_struct->f1 = 0.000000
注意,由於這裡並不存在真正的結構體變數,num 與 f1 的值是不確定的——程式只是把 ptr_ch 往回減去一個偏移量,讀到了不相干的記憶體。
這正說明了 container_of 的使用前提:傳入的 ptr 必須真的是某個配置好的結構體中該成員的位址,否則回推的結果毫無意義,而且這種錯誤在編譯期完全查不出來。另外要留意巨集中的 ({ ... }) 是 GNU 的 statement expression 擴充,因此這段程式碼不可攜;而 typeof 與 __mptr 的引入則是為了型別安全——它讓編譯器在你傳入錯誤型別的指標時直接報錯,而不是安靜地產生錯誤結果。這也是內核鏈表、工作佇列等大量使用 container_of 的原因:它把「從節點回到容器」這個動作變成一行可讀的程式碼。