在写linux内核驱动的时候,往往都是存在结构体的多层嵌套,那么如何通过结构的某个成员获取到整个结构体的指针呢?内核提供了一个宏container_of
,比如下面自定义的一个结构体struct module_info
struct module_info {
char *author;
unsigned int version;
};
通过结构体成员version或者是author可以获取指向该结构体的指针。
//include/linux/kernel.h
/**
* 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) ({ \
void *__mptr = (void *)(ptr); \
BUILD_BUG_ON_MSG(!__same_type(*(ptr), ((type *)0)->member) && \
!__same_type(*(ptr), void), \
"pointer type mismatch in container_of()"); \
((type *)(__mptr - offsetof(type, member))); })
还是以上边结构体为例子,通过结构体成员author获取到指向结构体module_info的指针。
struct module_info my_module;
struct module_info *my_module_ptr;
my_module_ptr = container_of(&my_module.author, struct module_info, author);
container_of
考虑author
从该结构体开始处的偏移量,进而获得正确的指针位置,从指针 my_module_ptr
中减去字段name的偏移量,就可以得到结构体struct module_info
的指针。
注意事项:
1、在使用该宏时,需要某个结构体成员所在的结构已经分配内存。