讀linux kernel增廣見聞,可學到不少C的小技巧
之前就知道offsetof 好用,不過就只有寫asm時偶爾炫技一下
最近才知道原來offsetof真正的威力是用在container_of
offsetof 是個macro,一般在stddef.h 應該會有
如果沒有的話就長得像下面這樣
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
是用來取得MEMBER在TYPE中的offset
而container_of 也是個macro,長得像下面這樣
#include <stddef.h>
#define container_of(ptr, type, member) ((type *)((uintptr_t)(ptr) - offsetof(type, member)))
是用來取得包含member的type *,ptr就是給member的位址
下面是container_of的使用範例:
struct some_existing_strct
{
...
};
struct ext_some_existing_struct
{
struct some_existing_struct _struct;
int new_member;
};
void foo(struct some_existing_struct *ptr)
{
struct ext_some_existing_struct *ext = container_of(ptr, struct ext_some_existing_struct, _struct);
do_something(ptr);
ext_do_something(ext);
}