Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

kernel/os: Add helper CONTAINER_OF macro #1508

Merged
merged 1 commit into from Nov 8, 2018

Conversation

andrzej-kaczmarek
Copy link
Contributor

This is a convenience macro to calculate original pointer of "parent"
object using a pointer to one of its members. It's commonly used in
e.g. Linux kernel and Zephyr Project so it should be also useful in
Mynewt :)

For example, with following structure:

struct foo {
    int a;
    struct bar bar;
    int c;
}

Let's assume we have:

struct foo g_foo;
struct bar *x = &g_foo.bar;

And we can use CONTAINER_OF to calculate pointer to g_foo using x:

struct foo *foo = CONTAINER_OF(x, struct foo, bar);

This is a convenience macro to calculate original pointer of "parent"
object using a pointer to one of its members. It's commonly used in
e.g. Linux kernel and Zephyr Project so it should be also useful in
Mynewt :)

For example, with following structure:

  struct foo {
      int a;
      struct bar bar;
      int c;
  }

Let's assume we have:

  struct foo g_foo;
  struct bar *x = &g_foo.bar;

And we can use CONTAINER_OF to calculate pointer to "g_foo" using "x":

  struct foo *foo = CONTAINER_OF(x, struct foo, bar);
@@ -26,4 +26,8 @@
#define POINTER_TO_INT(p) ((int) ((intptr_t) (p)))
#define INT_TO_POINTER(u) ((void *) ((intptr_t) (u)))

/* Helper to retrieve pointer to "parent" object in structure */
#define CONTAINER_OF(ptr, type, field) \
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For this particular macro, I'd prefer container_of in small caps. To match offsetof(). But I'm not hung up on it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also considered it as a lowercase for the same reason and also this is how it's defined in Linux kernel - but since it's still not full consistent with offsetof (i.e. without underscore) I eventually did this as in Zephyr which has the advantage that we port some code from there so there will be less changes required :-)

@andrzej-kaczmarek andrzej-kaczmarek merged commit b9b3189 into apache:master Nov 8, 2018
@andrzej-kaczmarek andrzej-kaczmarek deleted the container-of branch November 8, 2018 15:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants