linux系统函数container_of浅析

来源:互联网 发布:php indexof 编辑:程序博客网 时间:2024/06/05 18:34

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

/**

*container_of - cast a member of a structure out to thecontaining structure

*@ptr: the pointer to the member.

*@type: the type of the containerstruct this is embeddedin.

*@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指向的成员变量的结构体;membertype结构体中的成员,类型与ptr指向的变量类型一样。
功能是根据ptr的指针,来获取包含ptr所指类型的type结构体的指针
该宏的实现思路:计算type结构体成员member在结构体中的偏移量,然后ptr的地址减去这个偏移量,就得出type结构变量的首地址。

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

Struct hello_android_dev {

int val;

struct semaphore sem;

struct cdev dev;

};

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

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

 

原创粉丝点击