offsetof和container_of
来源:互联网 发布:淘宝uujuly品牌女装 编辑:程序博客网 时间:2024/06/05 04:23
offsetof
offsetof根据结构体的类型和成员名来计算该成员距结构体首地址的偏移量。
offsetof 的一种实现如下:
#define offsetof(type, member) ((size_t)(&((type *)0)->member))
offsetof宏首先将0转换为结构体指针类型,然后引用成员变量并取其地址。由于结构体首地址为0,所以成员变量的地址即为成员距结构体首地址的偏移量。
上面这种定义方法需要编译器的支持,现代编译器中一般采用下面的宏定义:
#define offsetof(type, member) __builtin_offsetof(type, member)
container_of
container_of根据成员地址、结构体类型和成员名来计算结构体的首地址,其定义如下:
#define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );})
示例代码
#include <stdio.h>#include <stddef.h>#define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );})struct foo{ char a; char b[10]; char c;};intmain(int argc, char *argv[]){ struct foo st; st.a = 1; printf("offset of a is %d\n", (int)offsetof(struct foo, a)); printf("offset of b is %d\n", (int)offsetof(struct foo, b)); printf("offset of c is %d\n", (int)offsetof(struct foo, c)); struct foo* pst; pst = container_of(&st.c, struct foo, c); printf("a = %d\n", pst->a);}
参考
[1] http://www.cnblogs.com/Anker/p/3472271.html
[2] http://en.wikipedia.org/wiki/Offsetof
[3] http://www.cplusplus.com/reference/cstddef/offsetof/
0 0
- offsetof和container_of
- offsetof和container_of
- offsetof和container_of总结
- container_of 和 offsetof 宏详解
- offsetof宏和container_of宏
- offsetof,container_of
- offsetof和container_of两个内核中的宏
- 两个重要的宏 offsetof 和 container_of
- offsetof typeof container_of 浅析
- container_of,offsetof,与typeof
- offsetof与container_of宏
- 内核:offsetof + container_of 分析
- offsetof、container_of 实现
- typeof、offsetof、container_of
- offsetof ,container_of ,typeof 用法
- container_of与offsetof详解
- offsetof与container_of宏
- offsetof与container_of
- java高新之类加载器
- Drazil and Factoria
- 只能通过chrome网上应用商店安装该程序”的解决方法
- 黑马程序员——C 语言指针总结
- 20150403杂记
- offsetof和container_of
- C语言字符串常见操作
- 黑马程序员——C语言基础语法--关键字、数据、变量
- Maven中央仓库无法更新jar包的解决办法
- T001_UT001_0001
- linux 下查看文件修改时间 等
- Java Struts 实现拦截器
- 最少拦截系统
- 黑马程序员Java基础第四章-----面向对象的概念及封装