当前位置:网站首页>container of()函数简介

container of()函数简介

2022-06-25 17:18:00 heater404

container of()函数简介

#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#else
#undef offsetof
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif

#ifndef container_of
#define container_of(ptr, type, member) ({
       \ const typeof(((type *)0)->member) * __mptr = (ptr); \ (type *)((char *)__mptr - offsetof(type, member)); })
#else
#undef container_of
#define container_of(ptr, type, member) ({
       \ const typeof(((type *)0)->member) * __mptr = (ptr); \ (type *)((char *)__mptr - offsetof(type, member)); })
#endif

container_of的作用:已知结构体type的成员member的地址ptr,求解结构体type的起始地址。

img

type的起始地址=ptr-size。

1、offsetof中的0指针的使用

#include <stdio.h>
#include <stdint.h>

typedef struct
{
    
	char a;
	int b;
	char c;
} test_t;

int main()
{
    

	test_t test;

	printf("&test=%p\n", &test);
	printf("&test.c=%p\n", &test.c);

	printf("&((test_t*)0)->c=%d\n", (int)&((test_t *)0)->c);

	return 0;
}

输出结果为:

&test=000000b6e7dffd04
&test.c=000000b6e7dffd0c
&((test_t*)0)->c=8

自定义结构体中因为字节对齐要求,所以该结构体大小为4bytes*3=12bytes。

(test_t *)0:在这里0被强制转换为test_t *类型,它的作用就是作为指向该结构体起始地址的指针。

&((test_t *)0)->c:的作用就是求c到起始地址的字节数,,其实就是求相对地址,起始地址为0,则&c就是size的大小。(打印需要整型,所以有一个int强转)。

2、const typeof( ((type *)0)->member ) *__mptr = (ptr)中的严谨

如果开发者使用时输入的参数有问题:ptr与member类型不匹配,编译时便会有warnning, 但是如果去掉改行,那个就没有了,而这个警告恰恰是必须的(防止出错有不知道错误在哪里),它的作用是获取member的类型仅此而已。

3、总结

container_of(ptr, type,member)函数的实现包括两部分:

   1.  判断ptr 与 member 是否为同意类型

   2.  计算size大小,结构体的起始地址 = (type *)((char *)ptr - size)   (注:强转为该结构体指针)

现在我们知道container_of()的作用就是通过一个结构变量中一个成员的地址找到这个结构体变量的首地址。

container_of(ptr,type,member),这里面有ptr,type,member分别代表指针、类型、成员。
最后将代码修改为如下:

int main()
{
    

	test_t test;

	printf("&test=%p\n", &test);
	printf("&test.c=%p\n", &test.c);
	printf("&((test_t*)0)->c=%d\n", (int)&((test_t *)0)->c);

	printf("&test=%p\n", container_of(&test.c, test_t, c));
	printf("&test=%p\n", container_of(&test.c, typeof(test), c));

	return 0;
}

输出为:

&test=00000011341ffc44
&test.c=00000011341ffc4c
&((test_t*)0)->c=8
&test=00000011341ffc44
&test=00000011341ffc44

原网站

版权声明
本文为[heater404]所创,转载请带上原文链接,感谢
https://blog.csdn.net/zhudaokuan/article/details/125397309