如何将指向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
代码还是很简单的,内核中也实现了相应功能的宏。如下:
- 433 #define list_entry(ptr, type, member) \
- 434 container_of(ptr, type, member)
- 399 #define container_of(ptr, type, member) ({ \
- 400 const typeof( ((type *)0)->member ) *__mptr = (ptr); \
- 401 (type *)( (char *)__mptr - offsetof(type,member) );})
- 24 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
你还费解吗?
阅读(2017) | 评论(0) | 转发(1) |