Home > Enterprise >  use of container_of macro, with struct
use of container_of macro, with struct

Time:06-10

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?

CodePudding user response:

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