linux系统函数container_of浅析

Container_of是linux内核中常用到的一个宏macro,他的主要功能是根据包含在某个结构体中变量的指针来获取该结构体本身的指针,通俗讲就是根据结构体中成员变量中某个成员的首地址来获取该结构体的首地址

/**

 *container_of - cast a member of a structure out to the containing structure

 *@ptr:  the pointer to the member.

 *@type:        the type of the containerstruct this is embedded in.

 *@member: the name of the member within thestruct.

 *

 */

#define container_of(ptr, type, member) ({                       \

         consttypeof( ((type *)0)->member ) *__mptr = (ptr);    \

         (type*)( (char *)__mptr - offsetof(type,member) );})

其中 ptr是指向type结构体成员变量中正被使用的某个成员变量的指针(即首地址);type是包含ptr指向的成员变量的结构体;member是type结构体中的成员,类型与ptr指向的变量类型一样。
功能是根据ptr的指针,来获取包含ptr所指类型的type结构体的指针
该宏的实现思路:计算type结构体成员member在结构体中的偏移量,然后ptr的地址减去这个偏移量,就得出type结构变量的首地址。

写一个简单的小例子字符驱动

Struct hello_android_dev { 

             int val; 

             struct semaphore sem; 

             struct cdev dev; 

         }; 

cdev *pcdev= &idev; (这里是我随便赋值的,前提是idev是struct cdev类型,且已经存在的)

Struct hello_android_dev* hello_dev =container_of(pcdev,struct hello_android_dev,dev);(一目了然了吧)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值