开发者

C typedef function prototype with struct attempting to reference before defined.

开发者 https://www.devze.com 2023-03-24 16:13 出处:网络
I need to reference a struct that\'s not yet defined because the struct actually conatins the t开发者_运维技巧ypedef\'d function prototype.

I need to reference a struct that's not yet defined because the struct actually conatins the t开发者_运维技巧ypedef'd function prototype.

For example,

typedef int (MyCallbackFunction)(X * x, void * ctx);

typedef struct CallbackData {
  MyCallbackFunction * callback;
  void * ctx;
} CallbackData;

typedef struct X {
  char a;
  int b;
  int c;
  double d;

  CallbackData e;
} X;

What's the valid way to actually write this code/header ?


Just forward declare the relevant types - and you can make the function pointer part of the typedef:

struct X_;

typedef int (*MyCallbackFunction)(struct X_ * x, void * ctx);

typedef struct CallbackData_ {
  MyCallbackFunction callback;
  void * ctx;
} CallbackData;

typedef struct X_ {
  char a;
  int b;
  int c;
  double d;

  CallbackData e;
} X;


Just forward declare your typedefs

typedef struct X X;
typedef struct CallbackData CallbackData;

and then declare the structs later.


Yes, you can forward declare the struct and use it in the declaration of MyCallbackFunction where you don't need it to be a complete type.

struct X;
typedef int (MyCallbackFunction)(struct X * x, void * ctx);
0

精彩评论

暂无评论...
验证码 换一张
取 消