container_of宏用于根据已知结构体某个成员的地址得到整个结构体变量的地址,宏定义如下:
#define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );})
例如:
#define to_i2c_driver(d) container_of(d, struct i2c_driver, driver) static int i2c_device_match(struct device *dev, struct device_driver *drv) { /* ... */ struct i2c_driver *driver = to_i2c_driver(drv); /* ... */ }
1. typeof
typeof关键字是gcc对c的一个扩展,用于获取变量的类型,例如:
char ch; typeof (ch) *chptr; /* 相当于char *chptr */所以这里也仅仅是定义了一个结构体中某个成员的指针,然后将ptr赋值给这个指针。
#undef offsetof #ifdef __compiler_offsetof #define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER) #else #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) #endif