I have created a macro for initializing a structure with some data, including a callback function pointer because this code is extensively reused in my file. I am storing the function pointer so I can simply iterate over the structure without having to explicitly check the msg_id and call the corresponding handling function.
These lines of code are around line number 150 :
typedef struct my_struct {
some_list *child_list;
void *data;
void *msg_func;
int nesting_level;
int msg_id;
} my_struct_t;
#define MALLOC_STRUCT_WITH_BASIC_DATA(level, msg_id, data_arg) \
my_struct_t *new_child = NULL; \
MY_CALLOC(new_child, my_struct_t, 1, failure); \
LISTCREATE(new_child->child_list); \
new_child->data = data_arg; \
#define INIT_MY_STRUCT(level, msg_id, data_arg, child_func) \
if (some_condition_on_data_arg_is_satisfied(data_arg)) { \
MALLOC_STRUCT_WITH_BASIC_DATA(level, msg_id); \
new_child->msg_func = &child_func; \
(new_child->msg_func)(new_child, new_child->data); \
}
There are about 100 msg functions and the list will keep increasing in the future. Their declarations are around line 250 :
static void msg_function1(my_struct_t *st, data_type1 *ptr_data);
static void msg_function2(my_struct_t *st, data_type2 *ptr_data);
...
static void msg_functionn(my_struct_t *st, data_typen *ptr_data);
Finally, the macros are invoked around line number 580 and message handling functions are defined starting around line number 700.
I get a compilation error when the macro is encountered :
my_file.c:586: error: called object ‘new_child->msg_func’ is not a function
This is my first time using function pointers. I searched on stackoverflow and google and tried to eliminate possible causes, including ordering of function declaration and usage. Could someone please help me understand what am I doing wrong here? To note, I do not have permission to change the message handling functions' type to void * or something else.
CodePudding user response:
You need to have a function pointer not an "ordinary" void pointer in your structure.
typedef struct my_struct {
some_list *child_list;
void *data;
void (*msg_func)(my_struct_t *, void *);
int nesting_level;
int msg_id;
} my_struct_t;
Ten message functions should convert the void pointer to the correct object pointer
static void msg_function2(my_struct_t *st, void *vData)
{
data_type2 *ptr_data = vData;
/* ... */