红联Linux门户
Linux帮助

看linux/list.h的心得

发布时间:2007-02-26 09:53:04来源:红联作者:swallow
因为list用得瞒多因此,我看看linux 怎么实现list的,我先看,感觉跟其他链表没有好大区别,但是仔细看,还是看到几个帅的地方

在list_entry这里看到了mac

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

container_of是个宏,定义如下:

#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \ // typeof是gcc扩展,用于得知数据类型的,这句话作用大概是看ptr是否是结构体里成

//员变量member的类型,不是编译时将报错,类型检测的
(type *)( (char *)__mptr - offsetof(type,member) );})

offsetof是计算成员member在结构体的type里面的偏移数,用__mptr的地址减去偏移地址就可以得到type结构体的开始地址


container_of向上面这样定义展开后可以直接负值如下面这样

#include

int main(int argc,char argv[])
{
int x = 1,y = 2;
int m =
({
x++;
x + y;
});

fprintf(stdout,"----%d\n",m);
}


这种用法应该是gcc的扩展。
文章评论

共有 0 条评论