Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading