The callback function is called by the caller.
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.
When a callback function is called (usually an API function), the address of one of its own functions (this function is a callback function) is passed as a parameter to the called function. When needed, the called function calls the callback function using the passed address.
The callback function is written by yourself. You need to call another function. One of the parameters of this function is your callback function name. In this way, the system will call the callback function you write when necessary, so that you can complete what you want to do in the callback function.
B. How to define and implement a class member function as a callback function
To define and implement a class member function as a callback function, you need to do three things:
A. statement;
B. definition;
C. Set the trigger condition, that is, use your callback function name as a parameter in your function for the system to call
For example:
Declare callback function type
Typedef void (* FunPtr) (void );
Define callback Functions
Class
{
Public:
Static void callBackFun (void) // callback function, which must be declared as static
{
......
}
};
Set trigger conditions
Void Funtype (FunPtr p)
{
P ();
}
Void main (void)
{
Funtype (A: callBackFun );
}
C. Callback functions and API functions
The callback API is very similar. They all use cross-layer called functions. However, the difference is that the API is provided by the lower layer to the upper layer. Generally, this function is known to the upper layer. The callback is the opposite. It is provided by the upper layer to the lower layer, it is unknown to the lower layer and must be installed by the upper layer. This installation function is actually an API provided by the lower layer. After the installation, the lower layer does not know the name of this callback, however, it uses a function pointer to save the callback function. To call this function, you only need to reference this function pointer and related parameter pointers.
In fact, the callback function is written in the upper layer. The lower layer stores the function through a function pointer. When an event is triggered, the lower layer calls the upper layer function through the function pointer.
From he Hao column programmer interview 500