简体   繁体   中英

use of container_of macro, with struct

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?

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));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM