container_of用法及实现

时间:2023-03-09 04:06:08
container_of用法及实现
container_of 有的情况下,只知道 struct结构中莫个成员的指针,而需要知道整个struct的指针 (如网卡驱动里面,list)
struct DDD {
        int a;
        int b;
        int c;
        int d;};struct DDD  ddd;
|------------|  <-------  得到这个
|      a         |
|------------|
|      b         |
|------------|
|      c         |  <-------  已知这个
|------------|
|      d         |
|------------|

//得到成员在结构
#define offsetof(TYPE, MEMBER) ((unsigned int) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({ \
const typeof(((type *)0)->member) * __mptr = (ptr); \
(type *)((char *)__mptr - offsetof(type, member)); }) int main()
{
printf("ddd is %p and ddd.c is %p \r\n",&ddd,&ddd.c);
struct DDD * p= container_of(&ddd.c,struct DDD,c);
printf("calc p is %p \r\n",p);
return 0;
}
/*
output:
ddd is 0x601030 and ddd.c is 0x601038
calc p is 0x601030
结果与想象
*/