代码复制于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) ({
\
const

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

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



