container_of 是一个在 Linux 内核和其他 C 语言项目中常用的宏,用于从结构体的成员指针获取结构体的指针
struct student { char name[50]; int age; float gpa;};创建一个指向结构体成员的指针。例如,我们可以创建一个指向 student 结构体中 age 成员的指针:int *age_ptr = &some_student.age;使用 container_of 宏获取结构体的指针。为此,需要提供成员指针、结构体类型和成员名称。例如:#include<linux/kernel.h> // 如果在 Linux 内核中使用,需要包含此头文件// 如果在其他项目中使用,请确保已经定义了 container_of 宏struct student *student_ptr;student_ptr = container_of(age_ptr, struct student, age);现在,student_ptr 指向包含 age_ptr 所指向的 age 成员的 student 结构体。
注意:container_of 宏的实现可能因项目而异。在 Linux 内核中,它通常定义为:
#define container_of(ptr, type, member) ({ \ const typeof(((type *)0)->member)*__mptr = (ptr); \ (type *)((char *)__mptr - offsetof(type, member)); })这里的 typeof 是一个 GNU C 扩展,用于获取表达式的类型。offsetof 是一个标准 C 库函数,用于获取结构体成员在结构体中的偏移量。


