Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1019761
  • 博文数量: 297
  • 博客积分: 11721
  • 博客等级: 上将
  • 技术积分: 3431
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-25 10:21
文章分类

全部博文(297)

文章存档

2016年(9)

2011年(71)

2010年(137)

2009年(80)

分类: LINUX

2011-06-15 13:24:43


list_entry

  /* list_entry - get the struct for this entry
  * @ptr: the &struct list_head pointer.
  * @type: the type of the struct this is embedded in.
  * @member: the name of the list_struct within the struct.*/
  #define list_entry(ptr, type, member) ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

  我们使用list_entry()宏在linux链表中访问链表数据。

  原理为指针ptr指向结构体type中的成员member;通过指针ptr,返回结构体type的起始地址。

  定义中((size_t) &(type *)0)->member)意为:把0地址转化为type结构的指针,然后获取该结构中member成员的指针,并将其强制转换为size_t类型

如果我们有test_list结构:
  struct test_list{
  void *testdata;
  struct list_head list;};
  定义struct list_head *pos;
  则list_entry(pos,struct test_list, list) 就可以根据pos的值,获取test_list的地址,也就是指向test_list的指针,这样,我们就可以存取test_list->testdata字段了。

阅读(375) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~