How to properly define a function pointer in struct, which takes struct as a pointer?

后端 未结 4 828
慢半拍i
慢半拍i 2021-01-05 00:56

I have a struct with a callback function, the callback function needs a pointer to the structure in order to do its operation. How do I properly define these elements such t

4条回答
  •  误落风尘
    2021-01-05 01:28

    There are two ways to do it — for both your example structures. They are essentially isomorphic.

    1. Use a structure tag, as already shown in various other answers.

      typedef struct pr_PendingResponseItem
      {
          // some fields required for processing...
          int (*doAction)(struct pr_PendingResponseItem *pr);
      } pr_PendingResponseItem;
      
      typedef struct LinkedItem
      {
          struct LinkedItem *prev;
          struct LinkedItem *next;
          void * data;
      } LinkedItem;
      
    2. Use typedef to give a name to an incomplete structure type and use the typedef in the structure definition.

      typedef struct pr_PendingResponseItem pr_PendingResponseItem;
      struct pr_PendingResponseItem
      {
          // some fields required for processing...
          int (*doAction)(pr_PendingResponseItem *pr);
      };
      
      typedef struct LinkedItem LinkedItem;
      struct LinkedItem
      {
          LinkedItem *prev;
          LinkedItem *next;
          void * data;
      };
      

    Note that the structure tags are in a different namespace from the typedef names, so there is no need to use different names for the typedef and structure tag. Also note that in C++ the typedef would be unnecessary.

提交回复
热议问题