Reputation: 1187
I need to define a structure and a callback function type in C as follows:
typedef void (*callback)(struct XYZ* p);
struct {
int a;
int b;
callback cb;
} XYZ;
Now this code won't compile because each definition requires the other. What I mean is, if the callback definition comes first, it won't compile because it requires the struct to be defined. Similarly if the struct is defined first, it requires the callback to be defined. Maybe this is a stupid question, but is there a clean way to resolve such issues?
Currently my idea would be to use a void * as callback argument, and typecast it to struct XYZ inside the callback. Any ideas?
Upvotes: 5
Views: 10240
Reputation: 213458
I would recommend to use the following method:
typedef struct xyz // xyz is a struct tag, not a type
{
int a;
int b;
void (*callback) (struct xyz* p); // this definition is local, "temporary" until the function pointer typedef below
} xyz_t; // xyz_t is a type
typedef void (*callback_t) (xyz_t* p);
Now, as far as the caller is concerned, your struct is equivalent to this:
// This is pseudo-code used to illustrate, not real C code
typedef struct
{
int x;
int y;
callback_t callback;
} xyz_t;
Example of usage:
void func (xyz_t* ptr)
{ ... }
int main()
{
xyz_t some_struct =
{
1, // a
2, // b
&func // callback
};
xyz_t another_struct =
{ ... };
some_struct.callback (&another_struct); // calls func
}
Upvotes: 3
Reputation: 8053
Declare the struct
(without defining it yet) before the function typedef
:
struct XYZ;
typedef void (*callback)(struct XYZ* p);
struct XYZ { // also fixed an error where your struct had no name
int a;
int b;
callback cb;
};
Similar to declaring a function-prototype and calling it before its definition.
Upvotes: 10