问题描述
当我在浏览Linux内核中,我发现它被定义container_of宏如下:
when I was browsing linux kernel, I found 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) );})
如果我们使用宏如下:
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,结构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.
虽然第一开发
在你的榜样是指指针的名字第二个开发
指的名字一个结构成员。
While the first dev
in your example refers to the name of pointer the second dev
refers to the name of a structure 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;
}
和一个指向为int * my_ptr
到 this_data code>成员,你会使用宏来得到一个指向
结构容器* 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 code>的偏移量结构的开始考虑是必不可少的获取正确的指针位置。
Taking the offset of this_data
to the beginning of the struct into account is essential to getting the correct pointer location.
有效,你只需要减去该成员的偏移 this_data code>从你的指针
my_ptr
来得到正确的位置
Effectively you just have to subtract the offset of the member this_data
from your pointer my_ptr
to get the correct location.
这正是宏观的最后一行呢。
That's exactly what the last line of the macro does.
这篇关于了解Linux内核container_of宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!