You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mynewt.apache.org by an...@apache.org on 2018/11/08 15:00:44 UTC

[mynewt-core] branch master updated: kernel/os: Add helper CONTAINER_OF macro

This is an automated email from the ASF dual-hosted git repository.

andk pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-core.git


The following commit(s) were added to refs/heads/master by this push:
     new b9b3189  kernel/os: Add helper CONTAINER_OF macro
b9b3189 is described below

commit b9b318994d60c4015ffd89e2f5e2b8df9b64e580
Author: Andrzej Kaczmarek <an...@codecoup.pl>
AuthorDate: Mon Nov 5 17:17:47 2018 +0100

    kernel/os: Add helper CONTAINER_OF macro
    
    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);
---
 kernel/os/include/os/util.h | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/kernel/os/include/os/util.h b/kernel/os/include/os/util.h
index d84d0a3..b04c57f 100644
--- a/kernel/os/include/os/util.h
+++ b/kernel/os/include/os/util.h
@@ -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) \
+        ((type *)(((char *)(ptr)) - offsetof(type, field)))
+
 #endif