Home > database >  How can I register a simple callback function and pass arguments to that function?
How can I register a simple callback function and pass arguments to that function?

Time:04-06

What I would like to do is :

  • a simple function "register_function" allowing a user to indicate a callback function to call (that this user has implemented)
  • when calling that function with "call_callback", to be able to pass arguments like a buffer for example

Here is my code:

static void (*callback)(int *buffer, int size) = NULL;

void register_callback(void (*ptr)())
{
    (*callback) = ptr;
}

void call_callback(int *buffer, int size)
{
    (*callback)(buffer, size);
}

The problem is that I have a compile-time error in the register_callback declaration.

CodePudding user response:

In register_callback() the assignment is just:

void register_callback(void (*ptr)( int *buffer, int size ))
{
    callback = ptr;
}

Please note that I also added the parameter declarations to the definition of ptr so the compiler can check for the correct function pointer type passed (assuming you have an identical prototype)

  • Related