linux 内核 container_of 宏的原理

一:概述

        container_of 宏是 Linux 内核中一个非常经典、非常强大的 “结构体逆推”技巧,用于从某个结构体成员的指针,反推出这个成员所在的结构体指针。  

#define container_of(ptr, type, member) \
    ((type *)((char *)(ptr) - offsetof(type, member)))

二:它做了什么? 

        container_of 的核心思想就是:  结构体中的某个成员的地址 - 成员在结构体中的偏移量 = 整个结构体的起始地址!

 三:举个例子      

#include <stdio.h>
#include <stddef.h>  // 提供 offsetof

struct my_container {
    int id;
    char name[20];
    struct inner {
        int x;
        int y;
    } point;
};

// 模拟 container_of
#define container_of(ptr, type, member) \
    ((type *)((char *)(ptr) - offsetof(type, member)))

int main() {
    struct my_container c = { .id = 42, .point = { .x = 1, .y = 2 } };

    // 已知 point 的地址
    struct inner *p = &c.point;

    // 逆推出 my_container 指针
    struct my_container *orig = container_of(p, struct my_container, point);

    printf("original id = %d\n", orig->id);  // 输出 42
}

四:总结 

        内核中的很多子系统(如 device、list、ttm)都使用一个通用结构(比如 struct list_headstruct device), 然后通过 container_of 在需要时把它转换为“更具体”的结构体。 

        所有结构体“嵌套”在一起,方便管理;用 container_of 能轻松回到“容器结构体”。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑不溜秋的

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值