container_of与offsetof详解

来源:互联网 发布:temp编程 编辑:程序博客网 时间:2024/06/05 03:24

Linxu内核中宏container_of的作用是根据结构体成员的一个指针地址来获取整个结构体的地址,要想理解container_of,我们先来看看宏offsetof

我们先来看看宏offsetof

在Linux内核中是这样定义的:
#ifndef _LINUX_STDDEF_H
#define _LINUX_STDDEF_H
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif
一共4步
1. ( (TYPE *)0 ) 将零转型为TYPE类型指针;
2. ((TYPE *)0)->MEMBER 访问结构中的数据成员;
3. &( ( (TYPE *)0 )->MEMBER )取出数据成员的地址;
4.(size_t)(&(((TYPE*)0)->MEMBER))结果转换类型。巧妙之处在于将0转换成(TYPE*),结构以内存空间首地址0作为起始地址,则成员地址自然为偏移地址;

再来看看宏container_of

在Linux内核中是这样定义的:

#ifndef _LINUX_KERNEL_H
#define _LINUX_KERNEL_H
#include "stddef.h"
/**
* 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) );})
#endif

其中,typeof是GNU C对标准C的扩展,它的作用是根据变量获取变量的类型。因此,上述代码中的第2行的作用是首先使用typeof获取结构体域变量member的类型为 type,然后定义了一个type指针类型的临时变量__mptr,并将实际结构体变量中的域变量的指针ptr的值赋给临时变量__mptr

第三行代码分为三步:

1.(char *)__mptr转换为字节型指针。

2.(char *)__mptr - offsetof(type,member) )用来求出结构体起始地址(为char *型指针),

3.然后(type *)( (char *)__mptr - offsetof(type,member) )在(type *)作用下进行将字节型的结构体起始指针转换为type *型的结构体起始指针。

1 0
原创粉丝点击