A callback function is a function called by a function pointer. If you pass the pointer (address) of a function as a parameter to another function, when this pointer is used to call the function to which it points, we will say this is a callback function. The callback function is called by another party when a specific event or condition occurs instead of by the implementer of the function. It is used to respond to the event or condition.
The above is the definition of Baidu encyclopedia. Let's take a simple example.
# Ifdef _ cplusplusextern "C" {# endif /**************************** **************************************** * **********/typedef int (* test_callback_func) (INT handle);/* defines the function pointer, point to the function entry address *//********************************* **************************************** * *****/# ifdef _ cplusplus} # endif # include <stdio. h> static test_callback_func y = NULL; typedef struct {int A; int B;} addnum; // two numbers in addition operation I NT flag = 0; // notification event static int test_callback (test_callback_func add, int handle) {int ret =-1; printf ("\ n {test_callback} start \ n "); if (add! = NULL) ret = 0; If (FLAG) // If flag is true, a notification event is reported, and the addition operation {flag = 0; y = add; (handle Y) (handle); // call function} printf ("{test_callback} End \ n"); return ret;} static int myadd (INT handle) // addition operation. The callback function {addnum * num; num = (addnum *) handle; // obtain two numbers for addition: printf ("\ n {myadd} start \ n"); printf ("% d + % d = % d \ n ", num-> A, num-> B, num-> A + num-> B); printf ("{myadd} End \ n"); Return 0 ;} int main (void) {addnum num; int Handle; printf ("{main} start \ n"); scanf ("% d", & num. a, & num. b); handle = (INT) (& num); // obtain the data address if (test_callback (myadd, handle )! = 0) // assume that the callback is a thread running return-1; flag = 1; // assume that the flag set 1 here is the IF (test_callback (myadd, handle )! = 0) Return-1; printf ("{main} End \ n"); Return 0 ;}
If the running result is as follows:
/*{main} start5 6 {test_callback} start{test_callback} end {test_callback} start {myadd} start5+6=11{myadd} end {test_callback} end {main} end*/
First, enter the main function, enter the two numbers to be added, pass the struct pointer to the callback function, and then judge whether there is any event, that is, whether the flag is 1, the first is 0, so no callback, the second flag is set to 1, so the addition operation is called.
This is a simple example. I have seen a lot of callbacks in Android, but I am not quite clear about them. Now I am going to look at them in turn, and I feel much clearer.