The callback function of the vernacular

1. What is a callback function?

Emm, let's start with a common example in life:

1. The child tells his mother: wake me up at eight tomorrow morning. This is the calling function A.

2. When the mother arrives at eight o'clock the next morning, she calls the child "it's time to get up". This is the message response T.

3. The child gets up. This is callback function B.

(It can be seen that the main call function and the callback function are the first person to do it)

That is, the first person asks the second person to wait for something A (the main call function), and then when event A occurs at a certain time T (a message occurs), the second person tells the first person to complete event B accordingly (callback handler).

Uh, everyone may be more confused, why do you need to call back something so simple? Just do it in sequence. Well, please continue reading.

2. When to use the callback function?

Here's another real-life example:

The company needs to buy a batch of machines. A sends B to go. A must not want to call every 10 minutes to ask if B has bought it back, right? Of course, A will hope that B will tell you when he buys it back. This sound is the callback.

Because A does not know when B will complete after calling B (send him to buy a machine), and the only one who knows when B is completed is of course B itself, so when B completes, it will notify A through a callback function, He has already completed it, and only then does A know that the following operations should be performed.

So callbacks are more common in event-driven mechanisms.

Third, the realization of the callback function

 

#include <stdio.h>

typedef void (*pFuncCb) (int);//Define the callback function.

void callback1(int a)

{
    printf("callback function1 is called and parameter = %d\n", a);//打印1
}

void callback2(int a)

{
    printf("callback function2 is called and parameter = %d\n", a);//打印2
}

pFuncCb callback_function;

void lowerFunc(int n)

{
    int i;

    for(i = n; i < n+10; i ++)

        if(callback_function) callback_function(i);
}

intmain()

{
    callback_function = callback1;

    lowerFunc(1);// will print 1 ten times, 1 to 10

    callback_function =NULL;

    lowerFunc(10);//No printing.
  
    callback_function = callback2;

    lowerFunc(100);// will print ten times print 2, 100 to 110  

    return 0;

}

 

Fourth, callback implementation between different dlls

The mutual access between different dlls involves the transfer of addresses. When defining the callback function, add an address variable LPVOID pContext.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324779692&siteId=291194637