The use of VC callback function in depth

  • 2020-04-01 23:40:23
  • OfStack

The callback function is simply an event responder, each message in Windows can be understood as an event, and the response code for the event is defined by the user. The user defines the code for the event response, but Windows needs to know the location of the code (otherwise Windows does not know how to call it, which is useless), so the user needs to tell Windows the pointer to the callback function, the most typical example is to assign the callback function pointer value to the lpfnWndProc component in the window class structure (WNDCLASS).

The parameter format of the callback function is defined by the caller of the callback function (typically Windows), and the implementer of the callback function must follow this format. Windows programs are based on an event-driven model, which necessitated the use of callback functions.

For a thorough understanding of the callback function, take a look at SDK Samples. The message mapping mechanism in MFC has hidden the callback function of the window message response, which is also in line with the programming idea of C++. The callback function is a global function after all, which cannot be implemented in the class, while the purpose of the message mapping mechanism is to make the code of the message response finally encapsulated in the window class (a subclass of CWnd class).

If you have time, look at the MESSAGE_MAP macro. The message map is a callback function, but this callback function is used differently. Normal callbacks require you to provide an address, pass it to a function, and let it call it; The message mapping function, however, is defined by you, the MESSAGE_MAP macro to get the address, and implement its call.

A callback function is a function that a programmer cannot explicitly call; Calls are made by passing the address of the callback function to the caller. To implement a callback, you must first define a function pointer. Although the syntax of the definition is somewhat arcane, if you are familiar with the general method of function declaration, you will find that the declaration of a function pointer is very similar to the declaration of a function.
CODE:

#include "stdafx.h"
#include "stdio.h"
void (*fun1)();
void A()
{
 printf("fun1/n");
}
void caller(void(*fun1)())
{
 printf("fun1 start/n");
 fun1();
 printf("fun1 end/n");
}
bool func2(int * i)
{
 printf("From func2() = %d, Hello World!/n", (*i)++);
 return true;
}
void caller2(bool func2(int *),int *j)
{
 func2(j);
}
int main(int argc, char* argv[])
{
 printf("From main(), Hello World!/n");
 printf("/n");

 caller(A);
 int i = 0;
 for (int j = 0; j < 10; j++)
 {
  caller2(func2, &i); /
 }

 getchar();

 return 0;
}


Related articles: