Chinaunix首页 | 论坛 | 博客
  • 博客访问: 232019
  • 博文数量: 37
  • 博客积分: 933
  • 博客等级: 军士长
  • 技术积分: 511
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-16 10:15
文章分类
文章存档

2012年(1)

2011年(36)

分类: C/C++

2011-04-20 11:28:43

如何将指向list_head的指针p转化为指向宿主的指针?
#include
struct list_head {
        struct list_head *prev;
        struct list_head *next;
};
struct mm_struct {
        int a;
        int b;
        double c;
        struct list_head mmlist;
        unsigned int d;
};
struct mm_struct init_mm = { 19999 };
int main()
{
        struct mm_struct *pm = (struct mm_struct*)0;//calculator offset
        int offset = &(pm->mmlist);
        printf("offset of c: %d\n",&(pm->mmlist));
        struct list_head *pl = &init_mm.mmlist;
        struct mm_struct *pm1 = (struct mm_struct*)((int)pl - offset);//convert
        printf("pm1->a:%d\n",pm1->a);
}

[root@localhost study]# ./a.out
offset of c: 16
pm1->a:19999

代码还是很简单的,内核中也实现了相应功能的宏。如下:
  1. 433 #define list_entry(ptr, type, member) \
  2.  434 container_of(ptr, type, member)
  1. 399 #define container_of(ptr, type, member) ({ \
  2.  400 const typeof( ((type *)0)->member ) *__mptr = (ptr); \
  3.  401 (type *)( (char *)__mptr - offsetof(type,member) );})
  1. 24 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
你还费解吗?
阅读(2025) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~