了解Linux内核中的container_of宏 [英] Understanding container_of macro in the Linux kernel
问题描述
当我浏览Linux内核时,我发现了一个container_of
宏,其定义如下:
When I was browsing the Linux kernel, I found a container_of
macro which is defined as follows:
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
我了解container_of的作用,但我不明白的是最后一句话,即
I understand what does container_of do, but what I do not understand is the last sentence, which is
(type *)( (char *)__mptr - offsetof(type,member) );})
如果我们按如下方式使用宏:
If we use the macro as follows:
container_of(dev, struct wifi_device, dev);
最后一句话的对应部分是:
The corresponding part of the last sentence would be:
(struct wifi_device *)( (char *)__mptr - offset(struct wifi_device, dev);
看起来什么也没做. 有人可以在这里填补空白吗?
which looks like doing nothing. Could anybody please fill the void here?
推荐答案
您的用法示例container_of(dev, struct wifi_device, dev);
可能会误导您,因为您在此处混合了两个名称空间.
Your usage example container_of(dev, struct wifi_device, dev);
might be a bit misleading as you are mixing two namespaces there.
在您的示例中,第一个dev
指的是指针的名称,而第二个dev
指的是结构成员的名称.
While the first dev
in your example refers to the name of pointer the second dev
refers to the name of a structure member.
这种混淆很可能激起了所有人的头痛.实际上,引号中的member
参数是指在容器结构中为该成员指定的名称.
Most probably this mix up is provoking all that headache. In fact the member
parameter in your quote refers to the name given to that member in the container structure.
以该容器为例:
struct container {
int some_other_data;
int this_data;
}
还有指向this_data
成员的指针int *my_ptr
,您可以使用该宏通过以下方式获取指向struct container *my_container
的指针:
And a pointer int *my_ptr
to the this_data
member you'd use the macro to get a pointer to struct container *my_container
by using:
struct container *my_container;
my_container = container_of(my_ptr, struct container, this_data);
考虑到结构开头的this_data
偏移量对于获取正确的指针位置至关重要.
Taking the offset of this_data
to the beginning of the struct into account is essential to getting the correct pointer location.
实际上,您只需从指针my_ptr
中减去成员this_data
的偏移量即可获得正确的位置.
Effectively you just have to subtract the offset of the member this_data
from your pointer my_ptr
to get the correct location.
这正是宏的最后一行.
这篇关于了解Linux内核中的container_of宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!