linux 内核 container_of 宏的原理
一:概述
container_of
宏是 Linux 内核中一个非常经典、非常强大的 “结构体逆推”技巧,用于从某个结构体成员的指针,反推出这个成员所在的结构体指针。
#define container_of(ptr, type, member) \((type *)((char *)(ptr) - offsetof(type, member)))
二:它做了什么?
container_of 的核心思想就是: 结构体中的某个成员的地址 - 成员在结构体中的偏移量 = 整个结构体的起始地址!
三:举个例子
#include <stdio.h>
#include <stddef.h> // 提供 offsetofstruct my_container {int id;char name[20];struct inner {int x;int y;} point;
};// 模拟 container_of
#define container_of(ptr, type, member) \((type *)((char *)(ptr) - offsetof(type, member)))int main() {struct my_container c = { .id = 42, .point = { .x = 1, .y = 2 } };// 已知 point 的地址struct inner *p = &c.point;// 逆推出 my_container 指针struct my_container *orig = container_of(p, struct my_container, point);printf("original id = %d\n", orig->id); // 输出 42
}
四:总结
内核中的很多子系统(如 device、list、ttm)都使用一个通用结构(比如 struct list_head
、struct device
), 然后通过 container_of
在需要时把它转换为“更具体”的结构体。
所有结构体“嵌套”在一起,方便管理;用 container_of
能轻松回到“容器结构体”。