linux device driver container_of理解

http://blog.csdn.net/yinkaizhong/article/details/4093795

这个博客写的挺详细,再写下自己总结。

inode结构中包含  struct cdev *i_cdev

struct cdev是表示字符设备的内核的内部结构。当inode指向一个字符设备文件时,该字段包含了指向struct cdev 结构的指针

对于某个有一个结构体来表示,例如在

scull内部,通过 struct scull_dev来表示每个设备。在该结构体中包含 struct cdev  cdev

inode中的 i_cdev指针即指向scull结构体中的cdev,

现在已知inode指针,要获得scull_dev结构的指针或者地址就要用到container_of宏来实现。

在<linux/kernel.h>中有宏定义 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 typeof( ((type *)0)->member ) *__mptr = (ptr); \
 (type *)( (char *)__mptr - offsetof(type,member) );})

 

这个宏首先有个大括号{},里面有两个语句。当替换到程序中,是两行代码。

我自己刚开始,一直还在纳闷,这个分号怎么理解,基础不够扎实。剩下的就容易理解了。

关于offsetof见stddef.h中:
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
TYPE是某struct的类型

0是一个假想TYPE类型struct,

MEMBER是该struct中的一个成员.

由于该struct的基地址为0, MEMBER的地址就是该成员相对与struct头地址的偏移量.
关于typeof,这是gcc的C语言扩展保留字,用于声明变量类型.
const typeof( ((type *)0->member ) *__mptr = (ptr);意思是声明一个与member同一个类型的指针常量 *__mptr,并初始化为ptr.
(type *)( (char *)__mptr - offsetof(type,member) );意思是__mptr的地址减去member在该struct中的偏移量得到的地址, 再转换成type型指针. 该指针就是member的入口地址了.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值