container_of宏
在 C 语言中,container_of 是一个宏定义,可以通过指向结构体中的成员来获取该结构体的地址。它的定义如下:
#define container_of(ptr, type, member) \ ((type *)((char *)(ptr) - offsetof(type, member)))
其中,ptr 是指向结构体中某个成员的指针,type 是结构体类型,member 是结构体中的成员名。
使用 container_of 宏时,需要注意以下几点:
- 确保
ptr指针是有效的,并且指向的是结构体中的成员。 - 确保
member成员在结构体中的偏移量是已知的,可以使用offsetof宏来获取。 - 确保
type是正确的结构体类型,否则可能会导致未定义的行为和内存错误。
下面是一个示例,演示如何使用 container_of 宏:
1 #include <stddef.h> 2 #include <stdio.h> 3 4 #define container_of(ptr, type, member) \ 5 ((type *)((char *)(ptr) - offsetof(type, member))) 6 7 struct person { 8 char name[20]; 9 int age; 10 }; 11 12 int main() { 13 struct person p = {"Alice", 25}; 14 int *age_ptr = &p.age; 15 16 // Get the address of the containing struct 17 struct person *person_ptr = 18 container_of(age_ptr, struct person, age); 19 20 // Print the name and age 21 printf("Name: %s\nAge: %d\n", person_ptr->name, person_ptr->age); 22 23 return 0; 24 }
这个例子创建了一个名为 person 的结构体,其中包含一个名为 name 的字符串和一个名为 age 的整数。然后,它创建了一个指向 age 成员的指针,并使用 container_of 宏获取包含此成员的结构体的地址。最后,它打印出该结构体中的 name 和 age 值。
それでも私の大好きな人

浙公网安备 33010602011771号