container_of的使用方法是什么

   2025-02-04 3060
核心提示:container_of 是一个 C 语言宏,用于通过结构体成员的指针获取包含该成员的结构体的指针。它的使用方法如下:#define container_

container_of 是一个 C 语言宏,用于通过结构体成员的指针获取包含该成员的结构体的指针。

它的使用方法如下:

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

参数说明:

ptr:指向结构体的某个成员的指针。type:结构体的类型。member:结构体中的成员名称。

container_of 宏通过使用 offsetof 宏来计算成员在结构体中的偏移量,然后将成员指针减去偏移量,得到结构体的指针。

以下是一个使用 container_of 宏的示例:

#include <stddef.h>struct Person {    char name[20];    int age;};int main() {    struct Person p = {"John Doe", 25};    int *p_age = &p.age;    struct Person *p_ptr = container_of(p_age, struct Person, age);    printf("Name: %s\n", p_ptr->name);    printf("Age: %d\n", p_ptr->age);    return 0;}

输出结果:

Name: John DoeAge: 25

在上面的示例中,通过 container_of 宏,我们可以通过 p.age 的指针 p_age 获取到包含该成员的结构体 struct Person 的指针 p_ptr,然后就可以访问结构体中的其他成员了。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言