container_of宏

发布时间 2023-04-07 10:51:36作者: 阿玛尼迪迪

  在 C 语言中,container_of 是一个宏定义,可以通过指向结构体中的成员来获取该结构体的地址。它的定义如下:

#define container_of(ptr, type, member) \
    ((type *)((char *)(ptr) - offsetof(type, member)))

  其中,ptr 是指向结构体中某个成员的指针,type 是结构体类型,member 是结构体中的成员名。

  使用 container_of 宏时,需要注意以下几点:

  1. 确保 ptr 指针是有效的,并且指向的是结构体中的成员。
  2. 确保 member 成员在结构体中的偏移量是已知的,可以使用 offsetof 宏来获取。
  3. 确保 type 是正确的结构体类型,否则可能会导致未定义的行为和内存错误。

  下面是一个示例,演示如何使用 container_of 宏:

 1 #include <stddef.h>
 2 #include <stdio.h>
 3 
 4 struct person {
 5     char name[20];
 6     int age;
 7 };
 8 
 9 int main() {
10     struct person p = {"Alice", 25};
11     int *age_ptr = &p.age;
12 
13     // Get the address of the containing struct
14     struct person *person_ptr =
15         container_of(age_ptr, struct person, age);
16 
17     // Print the name and age
18     printf("Name: %s\nAge: %d\n", person_ptr->name, person_ptr->age);
19 
20     return 0;
21 }

  这个例子创建了一个名为 person 的结构体,其中包含一个名为 name 的字符串和一个名为 age 的整数。然后,它创建了一个指向 age 成员的指针,并使用 container_of 宏获取包含此成员的结构体的地址。最后,它打印出该结构体中的 nameage 值。