今天看linux代码,看到container_of函数,可以从结构体的成员指针,加上结构体类型,得到指向结构体头的指针,非常有趣。
这一段是container_of的宏定义
/Users/foursking/Documents/linux/linux-2.6.24/include/linux/kernel.h:
350
351 /**
352: * container_of - cast a member of a structure out to the containing structure
353 * @ptr: the pointer to the member.
354 * @type: the type of the container struct this is embedded in.
...
356 *
357 */
358: #define container_of(ptr, type, member) ({ \
359 const typeof( ((type *)0)->member ) *__mptr = (ptr); \
360 (type *)( (char *)__mptr - offsetof(type,member) );})看这段函数不大明白,于是我做了如下的实验,代码如下
#include <stdio.h>
struct list_head{
struct list_head *next,*prev;
};
struct test{
int a;
int b;
struct list_head *f_list;
int c;
};
//this code indicate the engine of container_of
int main(void)
{
struct list_head* ptr;
struct test* test1;
long offset=(long)&((struct test*)0)->f_list;
printf("offset: %ld\n",offset);
//we caculate the ptr offset in struct test
const struct test* __mptr=ptr;
(struct test*)((char *)__mptr-offset);
return 0;
//first, we point __mptr to ptr
//next, we minus offset in __mptr so we point to the first element
//of struct test
}
本文介绍了Linux内核中container_of宏的功能与实现原理,并通过一个简单的C语言实验演示了如何从结构体成员指针获取指向整个结构体的指针。
3766

被折叠的 条评论
为什么被折叠?



