Linux内核链表结构与container_of认识
发布时间:2021-11-25 17:13:24 所属栏目:PHP教程 来源:互联网
导读:Linux内核中链表结构: struct list_head{ struct list_head *next,*prev; } 该链表结构内嵌在需要链接的数据结构体中 struct nf_sockopts{ struct list_head list; int data; } 因此,我们通过链表访问数据节点时,通常只知道结构体中list字段的地址,如何
|
Linux内核中链表结构: struct list_head{ struct list_head *next,*prev; } 该链表结构内嵌在需要链接的数据结构体中 struct nf_sockopts{ struct list_head list; int data; } 因此,我们通过链表访问数据节点时,通常只知道结构体中list字段的地址,如何去推导出整个结构体的起始地址? 内核中定义了一个list_entry()的宏,来返回结构体起始地址。定义如下: #define list_entry(prt,type,member) container_of(ptr,type,member) 关于container_of见kernel.h中: /** * container_of - cast a member of a structure out to the containing structure * @ptr: the pointer to the member. * @type: the type of the container struct this is embedded in. * @member: the name of the member within the struct. * */ #define container_of(ptr, type, member) ({ / const typeof( ((type *)0)->member ) *__mptr = (ptr); / (type *)( (char *)__mptr - offsetof(type,member) );}) container_of在Linux Kernel中的应用非常广泛,它用于获得某结构中某成员的入口地址. 关于offsetof见stddef.h中: #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) TYPE是某struct的类型 0是一个假想TYPE类型struct,MEMBER是该struct中的一个成员. www.linuxidc.com 由于该struct的基地址为0, MEMBER的地址就是该成员相对与struct头地址的偏移量. 关于typeof,这是gcc的C语言扩展保留字,用于声明变量类型. const typeof( ((type *)0->member ) *__mptr = (ptr);意思是声明一个与member同一个类型的指针常量 *__mptr,并初始化为ptr. (type *)( (char *)__mptr - offsetof(type,member) );意思是__mptr的地址减去member在该struct中的偏移量得到的地址, 再转换成type型指针. 该指针就是member的入口地址了. ![]() (编辑:应用网_丽江站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |




浙公网安备 33038102330468号