container_of详解
#define container_of(ptr, type, member) ({ \
const typeof(((type *)0)->member) * __mptr = (ptr); \
(type *)((char *)__mptr - offsetof(type, member)); } )
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
container_of使用了C扩展关键字typeof,以及结构体成员变量偏移。下面来具体看看:
- ((type *)0)是将0强制转化为type *,也就是指向type类型的指针;
- ((type *)0)->member是访问type结构中的member成员;
- const typeof( ((type *)0)->member ) *__mptr 定义一个与((type *)0)->member同种类型的指针变量(const变量);
- const typeof( ((type *)0)->member ) *__mptr=(ptr)对常量指针变量__mptr赋值,__mptr=ptr;
- (char *)__mptr - offsetof(type,member) 将__mptr强制转化为char类型指针,也就是__mptr;
- ((size_t) &((TYPE *)0)->MEMBER得到member在type结构体中的偏移量的地址,然后减去member在结构体中的偏移量,的到的自然就是结构体起始地址;
- (type *)( (char *)__mptr - offsetof(type,member) )最后再强制转化为(type *)类型得到ptr所在的结构体对象。
取得结构体一个字段的偏移地址的方法 offsetof(type,member) 宏,设置的十分巧妙,取得偏移后,具体对象的member地址-偏移地址,得到type对象的起始地址,设计相当的妙。
分享到:
相关推荐
名称container_of - 获取指向包含结构成员的结构的指针概要#include "container_of.h" container_of(member_pointer, contains_struct, struct_member);描述container_of() 宏返回一个指向包含该结构体成员的结构体...
「安全教育」Is_my_Container_Secure?Study_of_Vulnerability_in_Container_World - 身份管理 漏洞预警 数据库审计 攻防靶场 安全热点 解决方案
在内核代码中,经常见到container_of函数,它是一个宏定义,定义在include\linux\kernel.h文件中 /** * Container_of - cast a member of a structure out to the containing structure (将一个结构体的成员包含...
信息安全_数据安全_Container_Security_at_the_Speed_of_CI_CD 应急响应 安全测试 基础设施 安全响应 态势感知
大家都知道Container_of在Linux内核中是一个常用的宏,用于从包含在某个结构中的指针获得结构本身的指针,通俗地讲就是通过结构体变量中某个成员的首地址进而获得整个结构体变量的首地址。这篇文章详细的介绍了...
HCIP-Cloud_Computing-Container_V1.0_培训教材 HCIP-Cloud_Computing-Container_V1.0_实验手册
deploy_container_with_gpu.sh
HCIP-Cloud_Computing-Container_V1.0_培训教材 HCIP-Cloud_Computing-Container_V1.0_实验手册
CIS_Alibaba_Cloud_Container_Service_For_Kubernetes_(ACK)_Benchmark_v1.0.0.zip
集成WEB浏览器到窗体里面,根据上次的窗体大小、位置来展示
Container_Fields_in_FMP12_en
Dragable_Container_Sample_Version_1_0_2源码例子。
在winform应用程序中嵌入外部的exe,使用简单
集装箱代理服务 此服务在容器外部运行,并在套接字上侦听请求。.../global/common/shared/das/container_proxy/server.py & CPID=$! # Start the container process shifter --image=centos:8 bash > #
Disk-Based_Container_Objects By Tom Nelson
HCIP-Cloud_Computing-Container_V1.0.zip
BPF_as_a_revolutionary_technology_for_the_container_landscape.pdf
TheNewStack_Book1_The_Docker_and_Container_Ecosystem.pdf
python库,解压后可用。 资源全名:testcontainer_python_minio-0.2.0-py3-none-any.whl