linux 内核container_of

#include <stdio.h>
#define offsetof(type, number) ((size_t) &((type *)0)->number)
#define container_of(ptr,type,member) ({           \
    const typeof(  ((type *)0)->member ) * _mptr = (ptr); \
    (type *)((char *)_mptr - offsetof(type,member) );}) 

struct structtest {
    int number;
    char name;
    float code;
};

int main(void)
{
    struct structtest test = {99,'c',3.14};
    char * temp = &test.name;
    printf ("the pointer is %p\n",&test.number);
    printf ("the pointer is %p\n",&test.name);
    printf ("the pointer is %p\n",&test.code);

    printf ("the pointer is %p\n",ttemp);
    struct structtest * structtemp = container_of(temp,struct structtest,name);
    printf ("the pointer is %p\n",structtemp);
    return 0;
}

container_of根据结构体成员指针,得到结构体首地址。

这里首先将结构体首地址指向0地址 ,之后根据typeof得到( ((type *)0)->member )指向的类型 定义类型指针,赋值
const typeof( ((type )0)->member ) _mptr = (ptr);

这里根据传入的结构体类型以及成员,得到相对应的偏移值 首先将结构体指向0地址,之后把指向number的指针转换为整数

#define offsetof(type, number) ((size_t) &((type *)0)->number)

先把成员指针值转换为char× 之后进行相减 就可以得到结构体首地址
(type )((char )_mptr - offsetof(type,member)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值