-1

Hej, I was wondering , can one get a container of the pointer using macro container_of in linux kernel? Can simmilar macro be used? F.ex

struct container {
int a;
struct *b;
};

Having *b how can obtain *container? Thank you

R Sahu
  • 204,454
  • 14
  • 159
  • 270
ozimki
  • 75
  • 8
  • Take a look at the answer to http://stackoverflow.com/questions/15832301/understanding-container-of-macro-in-linux-kernel – DrC Mar 04 '15 at 07:42

1 Answers1

1

b is a pointer to some random address independent of the container, you need to pass a pointer to pointer and then use offsetof:

#include <stdio.h>
#include <stddef.h>

struct item {
    int c;
};

struct container {
    int a;
    struct item *b;
};

#define item_offset offsetof(struct container, b)

void fn(struct item **b)
{
    struct container *x = (struct container *)((char *)b - item_offset);

    printf("b->container->a = %d, b->c = %d\n", x->a, x->b->c);
}

int main(void)
{
    struct container x;
    struct item b = {20};

    x.a = 10;
    x.b = &b;
    fn(&x.b);
    return 0;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94