曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 4130|回复: 0
打印 上一主题 下一主题

获得链表结构体指针 | list_entry()

[复制链接]

4917

主题

5879

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34382
跳转到指定楼层
楼主
发表于 2011-5-18 14:37:24 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
list_entry() 宏可以用来获得链表结构体指针,它定义在 include/linux/list.h 中:
[C++] 纯文本查看 复制代码
/**
 * 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) \
    container_of(ptr, type, member)

从定义可以看到,它实际上是 container_of(ptr, type, member) 宏 --- 该宏根据成员变量 member 的指针 ptr 获得该成员变量所在 type 类型数据结构的地址,然后返回该地址。

比如一个结构体为:
[C++] 纯文本查看 复制代码
struct testlist {
   long data;
   struct list_head list;
}

访问成员变量 data 可以通过 list_entry(list_ptr, struct testlist, list)->data 来获得。

示例:
[C++] 纯文本查看 复制代码
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/version.h>
#include <linux/list.h>

MODULE_LICENSE("Dual BSD/GPL");

struct module *m = &__this_module;
static int list_module_init (void)
{
        printk ("---------------------------\n");
        printk ("this_module_address1:0x%p\n", list_entry(&(m->list), struct module, list));
        printk ("this_module address2:0x%p\n", m);
        printk ("---------------------------\n");
        return 0;
}

static void list_module_exit (void)
{
        printk ("unload listmodule.ko\n");
}

module_init(list_module_init);
module_exit(list_module_exit);

上面对两个地址的打印应该是一样的:
---------------------------
this_module_address1:0xf7e9f100
this_module address2:0xf7e9f100
---------------------------

关于内核链表描述可参考:http://www.groad.net/bbs/read.php?tid-3181.html
关于 container_of 宏的具体分析可参考:http://www.groad.net/bbs/read.php?tid-1118.html
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2024-5-17 03:04 , Processed in 0.082165 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表