Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading