0

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!

2
  • From your example it is unclear what functions are casted. Commented May 28, 2014 at 18:32
  • To avoid the casting hack you could defined a separate Callback; for each possible function pointer type. Alternatively, you could write thunks (i.e. add a void(void*) function for each callback, and in those functions, call the target with the right parameters). The latter is more flexible. Commented May 28, 2014 at 22:45

1 Answer 1

2

As long as the function pointer was to a function that accepts that parameters, and you cast the function pointer to the original type there shouldn't be a problem. You can cast a function pointer to another function pointer if you cast to the original type before doing the call.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.