阅读源码的过程中有大量使用到宏,所以作为开篇,其中有很多宏功能极其强大但也很晦涩难懂,本文不对宏思路做细致分析,因为网上基本上都能找得到,那么这篇应该算一个索引吧,只是为了本人记忆及查找方便
-
container_of
如果知道一个结构体中某个变量的指针,那么该宏就可以返回该变量对应的结构体指针
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
// 示例
#include <stdio.h>
#define offsetof(TYPE,MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
int main(int argc, char *argv[])
{
struct test {
int param_a;
int param_b;
} t = {100, 200};
int *p_b = &t.param_b;
struct test *ptr = container_of(p_b, struct test, param_b);
printf("param_a:%d\nparam_b:%d\n", ptr->param_a, ptr->param_b);
}