I need to declare a (typedef'd) structure and a (typedef'd) function reference in pain old C. This is my code:
typedef void (*monitor_calback)(monitor_data*, short int, short int, void*);
typedef struct
{
int port;
unsigned char port_state;
monitor_calback cb_high[8];
void *cb_high_data[8];
monitor_calback cb_low[8];
void *cb_low_data[8];
} monitor_data;
But of course it doen't compile because we don't know about the structure when the function reference is declared.
I have gotten this but it looks kinda messy and is a little hard to read.
struct _monitor_data;
typedef void (*monitor_calback)(struct _monitor_data*, short int, short int, void*);
typedef struct _monitor_data
{
int port;
unsigned char port_state;
monitor_calback cb_high[8];
void *cb_high_data[8];
monitor_calback cb_low[8];
void *cb_low_data[8];
} monitor_data;
Are there any better ways to do this?
You can typedef a struct before defining it:
typedef struct _monitor_data monitor_data;
typedef void (*monitor_calback)(monitor_data*, short int, short int, void*);
struct _monitor_data
{
int port;
unsigned char port_state;
monitor_calback cb_high[8];
void *cb_high_data[8];
monitor_calback cb_low[8];
void *cb_low_data[8];
};
This will work fine as long as you don't try to reference the internal structure of monitor_data
before struct _monitor_data
is fully defined. All the compiler needs to know for your monitor_callback
definition is that monitor_data *
is a pointer to something so monitor_callback
is fine as long as the compiler knows that monitor_data
exists.
This sort of construct is the standard approach for defining opaque types in C, you'd just be un-opaquing your type rather than leaving it opaque.