我正在阅读John Madieu的《 Linux设备驱动程序开发》,有人说
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);
答案 0 :(得分:0)
这是由于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]
a prior SO question上有关于此问题的讨论。请注意,C++ has no such limitation; const
可以自由添加。
A kernel dev discussion建议在另一种__mptr
内部执行类型检查的方式替换container_of
,这样您可能会发现它已经不再影响您。