container_of 宏不适用于 char* 或数组成员

标签 c pointers linux-kernel linux-device-driver

我正在阅读 John Madieu 的 Linux Device Drivers Development,其中一段说

The container_of macro won't work for char * or array members. It
means the first member of container_of must not be a pointer to
another pointer to char nor to array in the structure.

这是 container_of 的定义:

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

如果我有

struct person {
int age;
int salary;
char *name;
} me;

我有 char ** my_name = &(me.name);,为什么我不能执行以下操作:

struct person * me = container_of(my_name,struct person,name);

最佳答案

这是由于 ISO C 关于指针初始化的规则,在这种情况下会破坏 __mptr 的初始化。

这是一个简单的例子:

int main()
{
    char ar[5] = {0};
    const char (*ptr)[5] = &ar;
}

// warning: pointers to arrays with different qualifiers are incompatible in ISO C [-Wpedantic]

( live demo )

a prior SO question 上有关于这个问题的讨论。 .注意 C++ has no such limitation ; const 可以自由添加。

A kernel dev discussion建议将 __mptr 替换为另一种在 container_of 中执行类型检查的方法,因此您可能会发现这已经不再影响您。

关于container_of 宏不适用于 char* 或数组成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54008138/

相关文章:

在函数返回之间进行选择

c - 通过netlink获取VLAN接口(interface)的真实设备

swift - 使用 AudioFileGetProperty() 和 kAudioFilePropertyDataFormat 后发现可选值 nil

Linux 内核导出符号

c - 被调用的函数在被调用后如何返回给调用者?

带有结构的 C 数组 - 不能更改变量

c - 用什么来描述 C 中的指针是一个很好的现实世界隐喻?

C 通过函数对 char 进行 malloc/free 双指针

c - Linux内核3. *系列在通过make-kpkg和gcc-4.8.5在Ubuntu 16.04.1中自定义编译后无法正常启动。

cuda - 内核模式 GPGPU 使用