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 庫函數,用于獲取結構體成員在結構體中的偏移量。