multi inheritance with list_head.

  1. typedef struct OLNode {
  2. int LineNumber, ColumneNumber;
  3. ElemType value;
  4. struct OLNode *right, *down;
  5. }OLNode, *OList;

Find History

linux-address-inheritance.svg

Offset

small test

  1. #include <stdio.h>
  2. #include <stddef.h>
  3. typedef struct list_head {
  4. int count;
  5. }list_head ;
  6. int ref(struct list_head *obj) {
  7. return obj->count;
  8. }
  9. #define CustomTransfer_T(a) ( (_customObject*) ( ((char*)a) - \
  10. offsetof(_customObject,obj_T) ) )
  11. typedef struct _customObject {
  12. int obj;
  13. int obj_T;
  14. int extra;
  15. }_customObject;
  16. int sum(_customObject *obj) {
  17. return obj->extra+ ref((list_head*)&obj->obj) + ref((list_head*)&obj->obj_T);
  18. }
  19. void main() {
  20. _customObject custom = {10,11,12};
  21. printf("%d\n",ref((list_head*)&custom.obj));
  22. printf("%d\n",ref((list_head*)&custom));
  23. printf("%d\n",ref((list_head*)(&custom.obj_T)));
  24. list_head* parent_T = (list_head*)&custom.obj_T;
  25. printf("%d\n",sum(CustomTransfer_T(parent_T)));
  26. }

Linux 2.4

Linux 2.4 版本中还是最初质朴的定义, 最好研究
https://elixir.bootlin.com/linux/2.4.31/source/include/linux/list.h#L187

  1. /**
  2. * list_entry - get the struct for this entry
  3. * @ptr: the &struct list_head pointer.
  4. * @type: the type of the struct this is embedded in.
  5. * @member: the name of the list_struct within the struct.
  6. */
  7. #define list_entry(ptr, type, member) \
  8. ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

Linux 5.9

Linux 5.9 版本中 从 list 寻找 structure 的函数定义转移到了 /include/linux/kernel
https://elixir.bootlin.com/linux/v5.9-rc8/source/include/linux/kernel.h#L1000

  1. /**
  2. * container_of - cast a member of a structure out to the containing structure
  3. * @ptr: the pointer to the member.
  4. * @type: the type of the container struct this is embedded in.
  5. * @member: the name of the member within the struct.
  6. *
  7. */
  8. #define container_of(ptr, type, member) ({ \
  9. void *__mptr = (void *)(ptr); \
  10. BUILD_BUG_ON_MSG(!__same_type(*(ptr), ((type *)0)->member) && \
  11. !__same_type(*(ptr), void), \
  12. "pointer type mismatch in container_of()"); \
  13. ((type *)(__mptr - offsetof(type, member))); })