使用container_of宏的使用,结构

发布于 2025-02-06 06:02:44 字数 411 浏览 2 评论 0原文

我遇到了使用container_of的一件代码。

typedef struct api_1 api_2;

typedef void (*api_set)(api_2 *api, int a);

struct api_1{
    api_set set;
};

typedef struct{
    api_2 api;
    int value;
} api_p_t;

void set(api_2 *api, int a){
    api_p_t *priv_api = container_of(api, api_p_t, api);
    priv_api->value = a;
}

请向我解释,为什么“ container_of(API,API_P_T,API)”使用参数“ API”两次?是某种多态性行为吗?

I came across piece of code that uses container_of.

typedef struct api_1 api_2;

typedef void (*api_set)(api_2 *api, int a);

struct api_1{
    api_set set;
};

typedef struct{
    api_2 api;
    int value;
} api_p_t;

void set(api_2 *api, int a){
    api_p_t *priv_api = container_of(api, api_p_t, api);
    priv_api->value = a;
}

Please explain me, why "container_of(api, api_p_t, api)" uses parameter "api" twice? Is it some kind of polymorphic behaviour?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黑寡妇 2025-02-13 06:02:44

显然,这是Linux内核宏:

#define container_of(ptr, type, member) ({               \ 
   const typeof(((type *)0)->member) * __mptr = (ptr);   \ 
   (type *)((char *)__mptr - offsetof(type, member)); })

因此,第一个apiapi_2指针命名api,它作为参数传递给了函数。第二个apiapi_p_t成员名为api

api_p_t *priv_api = ({
    const typeof(((api_p_t *)0)->api) * __mptr = (api);
    (api_p_t*)((char *)__mptr - offsetof(api_p_t, api));
});

Apparently this is a Linux Kernel macro:

#define container_of(ptr, type, member) ({               \ 
   const typeof(((type *)0)->member) * __mptr = (ptr);   \ 
   (type *)((char *)__mptr - offsetof(type, member)); })

So, the first api is the api_2 pointer named api that is passed in as a parameter to the function. The second api is the api_p_t member named api.

api_p_t *priv_api = ({
    const typeof(((api_p_t *)0)->api) * __mptr = (api);
    (api_p_t*)((char *)__mptr - offsetof(api_p_t, api));
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文