内核中的container_of

本文详细讲解了在Linux内核编程中,如何通过container_of宏从结构体成员出发获取整个结构体指针的方法,以`structmodule_info`为例,并强调了使用前提和注意事项,包括确保成员已分配内存。
摘要由CSDN通过智能技术生成

在写linux内核驱动的时候,往往都是存在结构体的多层嵌套,那么如何通过结构的某个成员获取到整个结构体的指针呢?内核提供了一个宏container_of,比如下面自定义的一个结构体struct module_info

struct module_info {
	char *author;
	unsigned int version;
};

通过结构体成员version或者是author可以获取指向该结构体的指针。

//include/linux/kernel.h

/**
 * container_of - cast a member of a structure out to the containing structure
 * @ptr:        the pointer to the member.	//指向结构体某个成员的指针
 * @type:       the type of the container struct this is embedded in.	//结构体类型
 * @member:     the name of the member within the struct.	//结构体成员名
 *
 */
#define container_of(ptr, type, member) ({                              \
        void *__mptr = (void *)(ptr);                                   \
        BUILD_BUG_ON_MSG(!__same_type(*(ptr), ((type *)0)->member) &&   \
                         !__same_type(*(ptr), void),                    \
                         "pointer type mismatch in container_of()");    \
        ((type *)(__mptr - offsetof(type, member))); })

还是以上边结构体为例子,通过结构体成员author获取到指向结构体module_info的指针。

struct module_info my_module;
struct module_info *my_module_ptr;

my_module_ptr = container_of(&my_module.author, struct module_info, author);

container_of考虑author从该结构体开始处的偏移量,进而获得正确的指针位置,从指针 my_module_ptr中减去字段name的偏移量,就可以得到结构体struct module_info的指针。

注意事项:
1、在使用该宏时,需要某个结构体成员所在的结构已经分配内存。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值