Chinaunix首页 | 论坛 | 博客
  • 博客访问: 338274
  • 博文数量: 73
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 421
  • 用 户 组: 普通用户
  • 注册时间: 2013-08-03 15:18
个人简介

做笔记用,多为转载。

文章分类

全部博文(73)

文章存档

2016年(2)

2015年(29)

2014年(19)

2013年(23)

我的朋友

分类: LINUX

2014-06-22 22:43:33

http://blog.csdn.net/tigerjibo/article/details/8299589

1> Container_of在Linux内核中是一个常用的宏,用于从包含在某个结构中的指针获得结构本身的指针,通俗地讲就是通过结构体变量中某个成员的首地址进而获得整个结构体变量的首地址。
2>接口:

点击(此处)折叠或打开

  1. /**
  2.  *container_of-cast a member of a structure outtothe containing structure
  3.  *@ptr:    the pointertothe member.结构体中member成员的地址
  4.  *@type:    the type of the container struct thisisembeddedin.结构体类型,其成员包含member
  5.  *@member:    the name of the member within the struct.结构体成员
  6.  *
  7.  */
  8. #define container_of(ptr,type,member)({            \
  9.     consttypeof(((type*)0)->member)*__mptr=(ptr);    \
  10.     (type*)((char*)__mptr-offsetof(type,member));})

第一步,首先定义一个临时的数据类型(通过typeof( ((type *)0)->member )获得)与ptr相同的指针变量__mptr,然后用它来保存ptr的值。
说明:typeof是GNU C对标准C的扩展,它的作用是根据变量获取变量的类型《typeof关键字在linux 内核中很常见》
第二步,用(char *)__mptr减去member在结构体中的偏移量,得到的值就是整个结构体变量的首地址(整个宏的返回值就是这个首地址)。
2、offsetof
该宏用于求结构体中某个结构体成员在该结构体中的偏移量。
size_t offsetof( structName, memberName );
第一个参数是结构体的名字,第二个参数是结构体成员的名字。该宏返回结构体structName中成员memberName的偏移量。偏移量是类型的


阅读(1480) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~