Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointers and callbacks in C

I have started to review callbacks. I found this link on SO: What is a "callback" in C and how are they implemented? It has a good example of callback which is very similar to what we use at work. However, I have tried to get it to work, but I have many errors.

#include <stdio.h>

/* Is the actual function pointer? */
typedef void (*event_cb_t)(const struct event *evt, void *user_data);

struct event_cb
{
    event_cb_t cb;
    void *data;
};

int event_cb_register(event_ct_t cb, void *user_data);

static void my_event_cb(const struct event *evt, void *data)
{
    /* do some stuff */
}

int main(void)
{
    event_cb_register(my_event_cb, &my_custom_data);

    struct event_cb *callback;

    callback->cb(event, callback->data);

    return 0;
}

I know that callbacks use function pointers to store an address of a function. But there are a few things that I find I don't understand:

  • What is meant by "registering the callback" and "event dispatcher"?
like image 783
ant2009 Avatar asked Mar 10 '09 16:03

ant2009


People also ask

What is callback function or function pointer?

In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called as a Callback function. In C, a callback function is a function that is called through a function pointer.

What is callback function in C with example?

We can define it in other words like this: If the reference of a function is passed to another function argument for calling, then it is called the callback function. In C we have to use the function pointer to call the callback function. The following code is showing how the callback function is doing its task.

Why callback function is used in C?

What is the callback function in C? In C or any other programming language, we will give the function address to another function or any other code. So, that code can call the function at any time whenever it needs. A callback function is a function that is called by using a function pointer.

What is the use of function pointer in C?

Function Pointers point to code like normal pointers. In Functions Pointers, function's name can be used to get function's address. A function can also be passed as an arguments and can be returned from a function.


1 Answers

What is meant by "registering the callback" and "event dispatcher"?

"registering the callback" is the act of telling the underlying system which precise function to call, and (optionally) with which parameters, and possibly also for which particular class of events that callback should be invoked.

The "event dispatcher" receives events from the O/S (or GUI, etc), and actually invokes the callbacks, by looking in the list of registered callbacks to see which are interested in that event.

like image 60
Alnitak Avatar answered Sep 24 '22 06:09

Alnitak