本文的主要内容:
一、container_of的作用
二、container_of的定义
三、container_of的简单实现
一、container_of的作用
一般的我们通过结构体变量的地址可以找到其成员的地址,但是反过来一般是行不通的。在linux内核中就有这样的一个宏:container_of,它可以实现根据结构体成员的地址,找到这个结构体变量的地址,从而对结构体中的其他成员进行访问。
二、container_of的定义
container_of这个宏在Linux内核的tools\perf\util\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) ({ \
const typeof(((type *)0)->member) * __mptr

本文详细解析了Linux内核中container_of宏的作用,它能根据结构体成员地址反向获取整个结构体的地址。文章介绍了container_of的定义,并在toolsperfutilincludelinuxKernel.h中找到其源码。还通过一个简单的实例展示了如何使用container_of进行结构体成员的访问。
最低0.47元/天 解锁文章
418

被折叠的 条评论
为什么被折叠?



