I want to create a C module which handles Callbacks:
typedef struct {
int enable;
void (*callback)(void);
void *obj;
} Callback;
void Callback_Notify(Callback *me) {
if (me->enable && me->callback) me->callback(me->obj);
}
However, the modules which shall use this Callback module have callbacks with (different) parameters. My current solution is a preprocessor hack (left out the \):
#define Callback_Notify1Arg(me, cb_type, arg1)
if (me->enable && me->callback)
((cb_type)me->callback)(me->obj, arg1);
#define Callback_Notify2Arg(me, cb_type, arg1, arg2)
if (me->enable && me->callback)
((cb_type)me->callback)(me->obj, arg1, arg2);
Now a module using the Callback looks like the following:
typedef void (*SomeModuleCb_t)(int);
typedef struct { Callback cb; } SomeModule;
void SomeModule_DoSomething(SomeModule *me) {
int someData;
Callback_Notify1Arg((&me->cb), SomeModuleCb_t, someData);
}
The Code works! But I want to know if there is a stack corruption? Does the compiler allocate/deallocate the stack correctly around the Callback usage in SomeModule_DoSomething? For the memory allocation in the Callback struct does the callback pointer's signature matter?
Any better solutions for the topic are welcome!
Thanks for the clarification!
Callback;for each possible function pointer type. Alternatively, you could write thunks (i.e. add avoid(void*)function for each callback, and in those functions, call the target with the right parameters). The latter is more flexible.