container_of宏在嵌入式系统中的使用

   2024-09-30 5910
核心提示:container_of 宏是一个常用于 Linux 内核和其他 C 语言编写的嵌入式系统中的实用宏container_of 宏的主要作用是从一个成员变量的

container_of 宏是一个常用于 Linux 内核和其他 C 语言编写的嵌入式系统中的实用宏

container_of 宏的主要作用是从一个成员变量的指针,反向获取到包含该成员变量的结构体的指针。这在处理回调函数、链表操作等场景时非常有用。

以下是 container_of 宏的基本用法:

#define container_of(ptr, type, member) ({ \    const typeof(((type *)0)->member) *__mptr = (ptr); \    (type *)((char *)__mptr - offsetof(type, member)); })

这里有一个简单的例子来说明如何在嵌入式系统中使用 container_of 宏:

#include<stdio.h>#include <stddef.h>typedef struct {    int id;    char name[20];} student_t;int main() {    student_t student1 = {1, "Alice"};    student_t student2 = {2, "Bob"};    // 获取 student1 的 name 成员的指针    char *name_ptr = &student1.name;    // 使用 container_of 宏获取包含 name 成员的 student_t 结构体的指针    student_t *student_ptr = container_of(name_ptr, student_t, name);    // 输出结果    printf("Student ID: %d\n", student_ptr->id);    printf("Student Name: %s\n", student_ptr->name);    return 0;}

在这个例子中,我们首先定义了一个 student_t 结构体,然后创建了两个学生对象 student1student2。接着,我们获取了 student1name 成员的指针,并使用 container_of 宏获取了包含该成员的 student_t 结构体的指针。最后,我们输出了学生的 ID 和名字。

需要注意的是,container_of 宏依赖于 C 语言的特性(如 typeof 运算符和复合语句表达式),因此在使用时需要确保编译器支持这些特性。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号