container_of.h 1.8 KB

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