14

Can anyone please tell me,

  • what exactly is meant by registering a callback function in C (with some examples)?
  • what are Notify callbacks ?
  • what are Asynchronous call backs?
SachSK
  • 3
  • 3
Maddy
  • 503
  • 4
  • 12
  • 21
  • 2
    possible duplicate of [What is a "callback" in C and how are they implemented?](http://stackoverflow.com/questions/142789/what-is-a-callback-in-c-and-how-are-they-implemented) – Hasturkun Dec 21 '11 at 13:16
  • See also, http://stackoverflow.com/a/147241/20270 – Hasturkun Dec 21 '11 at 13:17
  • 1
    the wikipedia page is decent http://en.wikipedia.org/wiki/Callback_%28computer_programming%29 – LB40 Dec 21 '11 at 13:22
  • https://stackoverflow.com/questions/2152974/interrupt-safe-way-to-set-function-pointer-in-hitech-c-on-pic32 – Denys Yurchenko Oct 21 '18 at 12:49

2 Answers2

18

Registering a callback function simply means that you are arranging for an external entity to call your function.

It might happen at a later time, or it might happen straight away. A straightforward example is qsort. It is declared like this:

void qsort(void *base, size_t nel, size_t width,
       int (*compar)(const void *, const void *));

In order to use it, you must pass a pointer to a function that compares elements - the callback.

That was a simple example but generally "registering a callback" means passing a function pointer to someone who will call it for you in the future.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
7

Registering a callback means to pass a function pointer to the one who will call your function through the pointer

For easier understanding Consider A and B who are two entities involved in the code. A has written a function say myFunc

char myFunc(int a)
{
/* Code written by A*/
}

Now when it is said A will register a callback with B, it means A will send the function pointer to B By sending function pointer to B, A provides an access to the function

To register the callback there will be a function where A can pass the pointer A will call the function as

cb_register(myFunc);
// Passed the address of Function

This cb_register function is defined in B as

typedef void (*cb_fn_ptr)(int a);

void cb_register(cb_fn_ptr cb)
{
    // In this function B can store the address in a structure member

}

For example a struct_B is declared which stores

struct s_B {
    cb_fn_ptr cb;
    // cb will have address whenever B 
};

B has stored the address (which the function pointer points to) and can use it to call the function later.

When B calls the function through the function pointer it is called as callback. B just needs to know the prototype of the function to call the function and can be completely unaware of what the function does. In this case function will call as

struct s_B temp;
char ret_val;
int arg_val;
ret_val = temp->cb(arg_val)
//This is a callback
Omkar Kekre
  • 327
  • 2
  • 8