1、定义
#define rt_list_entry(node, type, member) \
rt_container_of(node, type, member)
#define rt_container_of(ptr, type, member) \
((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member)))
2、作用
rt_list_entry 这个宏的作用是通过结构体成员的地址,返回结构体的地址
3、解析
参数 node:结构体成员的地址
参数 type :结构体的类型
参数 member:结构体的成员
&((type *)0->member) 的作用是求成员 member 在 type 结构体中的相对偏移量
例如结构体
struct test_struct
{
int num1;
int num2;
float fl;
};
成员 num1 的相对偏移量是 0,成员 num2 的相对偏移量是 4,成员 fl 的相对偏移量是 8。
所以使用 ptr 的地址,减去结构体成员的相对地址,得到的就是结构体的地址。
示例程序如下
#include <stdio.h>
#define rt_list_entry(node, type, member) \
rt_container_of(node, type, member)
#define rt_container_of(ptr, type, member) \
((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member)))
struct test_struct
{
int num1;
int num2;
float fl;
};
int test_containerof(void)
{
struct test_struct init_test_struct = { 99, 18, 59.12 };
int *char_ptr = &init_test_struct.num1;
struct test_struct *test_struct = rt_container_of(char_ptr, struct test_struct, num1);
printf("init test struct address is %p\r\n", &init_test_struct);
printf("get test struct address is %p\r\n", test_struct);
if (&init_test_struct != test_struct)
{
printf("get struct address failed\r\n");
}
else
{
printf("get struct address successful\r\n");
}
printf("test_struct->num1 = %d\ntest_struct->num2 = %d\ntest_struct->fl = %f\n",
test_struct->num1, test_struct->num2, test_struct->fl);
return 0;
}
int main(int argc, char *argv[])
{
test_containerof();
while (1);
}
/*
init test struct address is 000000000062FDD0
get test struct address is 000000000062FDD0
get struct address successful
test_struct->num1 = 99
test_struct->num2 = 18
test_struct->fl = 59.119999
*/