欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

linux 内核container_of

程序员文章站 2024-01-23 16:10:40
...
#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)