container_of 是一个 C 语言宏,用于在已知成员变量的情况下获取其所属结构体的指针
#include<stdio.h>#include <stddef.h>typedef struct { int id; char name[20];} Student;使用 offsetof 计算成员变量在结构体中的偏移量。例如,计算 name 成员在 Student 结构体中的偏移量:size_t name_offset = offsetof(Student, name);printf("Offset of 'name' in Student: %zu\n", name_offset);编写一个简单的测试函数,模拟 container_of 宏的行为。例如:void* test_container_of(void* ptr, size_t offset) { return (char*)ptr - offset;}创建一个 Student 结构体实例,并获取其 name 成员的地址。然后使用测试函数获取结构体实例的地址,并检查结果是否正确。例如:int main() { Student student = {1, "Alice"}; void* name_ptr = &student.name; // 使用测试函数获取结构体实例的地址 Student* container_ptr = (Student*)test_container_of(name_ptr, name_offset); // 检查结果是否正确 if (container_ptr == &student) { printf("Test passed!\n"); } else { printf("Test failed!\n"); } return 0;}编译并运行程序,检查输出结果。如果输出 “Test passed!”,则说明 container_of 宏的行为与预期相符。注意:这个示例仅用于演示目的,实际上您应该直接使用编译器提供的 container_of 宏。在编写驱动程序或其他需要直接操作硬件的代码时,这种方法可能会很有用。


