c - Understanding container_of macro in the Linux kernel -
when browsing linux kernel, found container_of
macro defined follows:
#define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );})
i understand container_of do, not understand last sentence,
(type *)( (char *)__mptr - offsetof(type,member) );})
if use macro follows:
container_of(dev, struct wifi_device, dev);
the corresponding part of last sentence be:
(struct wifi_device *)( (char *)__mptr - offset(struct wifi_device, dev);
which looks doing nothing. please fill void here?
your usage example container_of(dev, struct wifi_device, dev);
might bit misleading mixing 2 namespaces there.
while first dev
in example refers name of pointer second dev
refers name of structure member.
most mix provoking headache. in fact member
parameter in quote refers name given member in container structure.
taking container example:
struct container { int some_other_data; int this_data; }
and pointer int *my_ptr
this_data
member you'd use macro pointer struct container *my_container
using:
struct container *my_container; my_container = container_of(my_ptr, struct container, this_data);
taking offset of this_data
beginning of struct account essential getting correct pointer location.
effectively have subtract offset of member this_data
pointer my_ptr
correct location.
that's last line of macro does.
Comments
Post a Comment