container_of.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #ifndef CCAN_CONTAINER_OF_H
  2. #define CCAN_CONTAINER_OF_H
  3. #include <stddef.h>
  4. #include "config.h"
  5. #include <ccan/check_type/check_type.h>
  6. /**
  7. * container_of - get pointer to enclosing structure
  8. * @member_ptr: pointer to the structure member
  9. * @containing_type: the type this member is within
  10. * @member: the name of this member within the structure.
  11. *
  12. * Given a pointer to a member of a structure, this macro does pointer
  13. * subtraction to return the pointer to the enclosing type.
  14. *
  15. * Example:
  16. * struct foo {
  17. * int fielda, fieldb;
  18. * // ...
  19. * };
  20. * struct info {
  21. * int some_other_field;
  22. * struct foo my_foo;
  23. * };
  24. *
  25. * static struct info *foo_to_info(struct foo *foo)
  26. * {
  27. * return container_of(foo, struct info, my_foo);
  28. * }
  29. */
  30. #define container_of(member_ptr, containing_type, member) \
  31. ((containing_type *) \
  32. ((char *)(member_ptr) - offsetof(containing_type, member)) \
  33. - check_types_match(*(member_ptr), ((containing_type *)0)->member))
  34. /**
  35. * container_of_var - get pointer to enclosing structure using a variable
  36. * @member_ptr: pointer to the structure member
  37. * @var: a pointer to a structure of same type as this member is within
  38. * @member: the name of this member within the structure.
  39. *
  40. * Given a pointer to a member of a structure, this macro does pointer
  41. * subtraction to return the pointer to the enclosing type.
  42. *
  43. * Example:
  44. * static struct info *foo_to_i(struct foo *foo)
  45. * {
  46. * struct info *i = container_of_var(foo, i, my_foo);
  47. * return i;
  48. * }
  49. */
  50. #ifdef HAVE_TYPEOF
  51. #define container_of_var(member_ptr, var, member) \
  52. container_of(member_ptr, typeof(*var), member)
  53. #else
  54. #define container_of_var(member_ptr, var, member) \
  55. ((void *)((char *)(member_ptr) - offsetof(containing_type, member)))
  56. #endif
  57. #endif /* CCAN_CONTAINER_OF_H */