container_of宏深度解析
作用: 由结构体中某个元素的指针,推出整个结构体变量的指针。 原型: #define container_of(ptr,type,member) {const typeof(((type*)0)->member)* _myptr=(ptr); (type*)((char*)_myptr-offsetof(type,member));}) 变量分析: ptr指向结构体元素member元素的指针;type为结构体类型;member为结构体中的某个元素;typeof为C语言的关键字,用来由变量得到变量的类型,eg;typeof(a)得到变量a的类型。 typeof(((type*)0)->member)* _myptr=(ptr)类似于(int)* p=(ptr)。 宏解析: 先用typeof得到member元素的类型,定义为一个指针( _myptr);然后用这个指针减去该元素相对于结构体首地址的偏移量,就得到整个结构体变量的首地址了,再把这个地址强制类型转换为type*即可(得到指针)。 举例: # include <stdio.h> struct mystruct { char a ; int b ; short c } ; # define container_of(ptr,type,member) { const typeof ( ( ( type * ) 0 ) ->