gpt4 book ai didi

c - 替换 linux 内核中使用的 container_of 宏

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:03:49 26 4
gpt4 key购买 nike

试图从源代码 linux 内核中了解 container_of() 的功能 Definition of container_of ,我发现宏定义中的下面一行看起来什么也没做。

const typeof( ((type *)0)->member ) *__mptr = (ptr); \

因此,我编写了一个没有上述行的简单 C 程序,并尝试比较获得的结果。基本上,我试图了解新实现 my_contianer_of()container_of() 有何不同? 当两个实现给出相同的结果时。

#include <stdio.h>
#include <stddef.h>

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

#define my_container_of(ptr, type, member) ({ \
(char *)ptr - offsetof(type, member);})

struct container {
int *i;
char c;
float f;
};

void foo(char *cptr)
{
printf("foo : %p\n", my_container_of(cptr, struct container, c));
}

int main(int argc, char *argv[])
{
struct container tc;

printf("&tc : %p\n", &tc);
printf("cof : %p\n", container_of(&tc.c, struct container, c));
printf("mycof: %p\n", my_container_of(&tc.c, struct container, c));

foo(&tc.c);

return 0;
}

下面是上述 c 程序的示例输出。

&tc  : 0x7ffca543e0c0
cof : 0x7ffca543e0c0
mycof: 0x7ffca543e0c0
foo : 0x7ffca543e0c0

请不要将此问题标记为与任何其他问题或此 Understanding container_of macro in the linux kernel 重复因为这些问题没有为我的查询提供所需的答案。

最佳答案

您的实现不是类型安全的。它不能确保您传递的指针与成员的类型相同,这可能会导致错误。所以,例如:

my_container_of(&tc.f, struct container, c)

将编译得很好。内核版本至少会发出有关不兼容指针类型的警告。或者完全导致编译停止,具体取决于您的 GCcflags。

当然,内核版本不会阻止所有 错误(例如,如果fc 是同一类型)。但这是它可以捕捉到的,而且应该捕捉到。

关于c - 替换 linux 内核中使用的 container_of 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52197464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com