Linux 的 container_of 原型定義如下:
container_of(ptr, type, member);
各參數含義:
舉個例子:
struct typeabc{
int mem0;
float mem2;
double mem4;
char mem6;
};
struct typeabc abc, *pabc;
abc.mem2 = 0.0;
float *pmem2 = &abc.mem2; // 已知成員位址
// 透過成員變數的位址,反推出它所屬結構的首位址
pabc = container_of(pmem2, struct typeabc, mem2);
核心概念是:當你手上只有某個成員的指標時,container_of 能藉由結構型態與成員名稱,把指標還原成整個結構的起始位址,這是 Linux 核心與驅動開發中非常常見的技巧。