container_of()一个在内核中经常使用的宏

container_of()是一个在内核中经常使用的宏,用于获取一个结构体指针所在它所属的结构体的指针。

宏的参数包括:

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

首先,宏container_of()确定了ptr指向的成员在结构体中的偏移(offset)。通过offsetof()宏就可以得到这个偏移,其参数为结构体类型和成员名称。得到偏移后,再通过减去偏移的方式得到指向整个结构体的指针。

具体实现如下:

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

其中,typeof是GCC的一个扩展关键字,用于返回一个表达式的类型。假设ptr指向的成员变量的类型为T,__mptr就是一个指向T类型的指针。然后,调用offsetof()即可得到member在type类型中的偏移量,最后返回一个指向type类型的指针。注意,尖括号不能省略,因为它表示类型转换。此外,container_of()宏使用了一个GCC的语言扩展"statement expression",即后面的{},可以在其中包含多条语句。

下面给出一个示例,用于说明container_of()的使用方法:

#include <stdio.h>
#include <stddef.h>

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

struct student {
    int id;
    char name[20];
};

int main() {
    struct student stu = {10001, "Zhang San"};
    char *pname = stu.name;
    struct student *pstu = container_of(pname, struct student, name);

    printf("ID: %d, Name: %s\n", pstu->id, pstu->name);
    return 0;
}

在上面的程序中,pname指向stu的name成员,通过container_of()宏获得了指向整个struct student结构体的指针pstu,然后就可以访问id和name成员了。

【最后一个bug】多平台都有更新和发布,大家可以一键三连,关注+星标,不错过精彩内容~
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Linux内核container_of是一个定义,用于获取包含某个成员的结构体变量的地址。它的定义可以在include/linux/kernel.h找到。该的作用是通过给定的成员指针,返回包含该成员的结构体变量的地址。具体的定义如下: ```c #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );}) ``` 这个使用非常方便,可以通过成员指针来获取整个结构体变量的地址。在进行内核驱动开发时,经常会用到这个来获取结构体变量的地址,以便进行相关操作。 #### 引用[.reference_title] - *1* [Linux内核:理解container_of](https://blog.csdn.net/qq_28877125/article/details/124209504)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Linux内核container_of的原理及其使用详解](https://blog.csdn.net/u010632165/article/details/107523477)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值