C语言#Linux-- 计算结构体成员偏移和成员反向计算结构体地址(container_of)

本文介绍了C语言在Linux环境中的结构体成员偏移计算,以及如何使用container_of宏来从成员地址反向获取整个结构体的地址。通过分析Linux内核中的代码,解释了typeof编译器扩展特性以及container_of宏的工作原理。运行gcc -E命令可以查看预处理后的语句,进一步理解其实现。
摘要由CSDN通过智能技术生成

代码复制于Linux内核:tools/include/linux/kernel.h
作用图:
在这里插入图片描述

功能:

  • 1、typeof是编译器扩展的特性(推断出类型),https://gcc.gnu.org/onlinedocs/gcc/Typeof.html#Typeof
  • 2、container_of:1、先报地址强制转换为特定成员地址,变量前_为了不冲突 2、计算成员偏移字节 3、再转换为char*,为了进行字节单位的地址运算 4、最终转换为结构体类型即可。。。 5、整个宏是一个复合语句,最后一个子表达式的值就是整个表达式的值。(也是编译器扩展特性,https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html)
#include <stdio.h>
#include <stdlib.h>



//复制于:tools/include/linux/kernel.h

#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif

#ifndef container_of
/**
 * 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) ({
     			\
	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值