最近看到一个宏定义如下:
/**
* rt_container_of - return the member address of ptr, if the type of ptr is the
* struct type.
*/
#define rt_container_of(ptr, type, member) \
((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member)))
因为程序中多次使用,所以对其进行了详细分析,过程如下:
这个宏的作用就是通过一个结构体的某个成员的指针,反推出这个结构体的首地址。这种操作非常有用,尤其在C语言中写面向对象的程序时,相当模拟了C++多态的效果。先写个小程序做个实验,验证一下(&((type *)0)->member)到底是什么结果:
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
typedef struct {
char a;
char b;
char c;
char d;
}test_t;
void main(void)
{
printf("offsetof: %d\n", offsetof(test_t, a));
printf("offsetof: %d\n", offsetof(test_t, b));
printf("offsetof: %d\n", offsetof(test_t, c));
printf("offsetof: %d\n"