What is callback?

Source: Internet
Author: User
Callback is used for inter-layer collaboration. The upper layer installs the function at the lower layer, which is the callback. The lower layer triggers the callback under certain conditions. For example, as a driver, it is an underlying layer, when he receives a data, in addition to processing the data at the current layer, he will also perform a callback to send the data to the upper application layer for further processing, which is common in hierarchical data communication.

Its real-time reconciliation API is very similar, and their commonalities are 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 the call provided by the higher 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 this callback. To call this callback, you only need to reference this function pointer and related parameter pointers. 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.



A callback function is a very useful and important concept. When an event occurs, the system or other functions automatically call a function. Callback functions are widely used in Windows programming, such as hook callback:
Mouseproc, getmsgproc, enumwindows, drawstate callback functions, and many other system-level callback processes.
I. Declare the callback function type. Typedef int (winapi * pfcallback) (intparam1, intparam2); in fact, it declares that a return value is int, and the input parameter is the pointer to the function of two intns. Since the C ++ and Pascal compilers may have different processing methods for parameter input stack and function return, the function types are modified in a unified manner using winapi (winapi macro expansion is _ stdcall) or stdcall.
Ii. Declare the original form of the callback function. Declare the original form of the function.
Int winapicbfunc (intparam1, intparam2 );
The above functions are global functions. If you want to use a function in a class as the original form of the callback function, declare the function as a static function.
Iii. Callback Function I put the callback function called by the caller to call the callback function into the DLL. This is a very simple win32dll generated by VC and outputs the function name testcallback using the def file. Implementation: pfcallback gcallback = 0;
Void winapi testcallback (pfcallbackfunc)
{
If (func = NULL) return;
Gcallback = func;
Dwordthreadid = 0;
Handlehthread = createthread (null, null, thread1, lpvoid (0), threadid );
Return;
}
This function saves the input pfcallbackfunc parameter for use and starts a thread. Declares a function pointer pfcallbackgcallback to save the input function address. The callback function is equivalent to an interrupt processing function, which is automatically called by the system when it meets your Preset conditions. To do this, you need to do three things: 1, Declaration; 2, definition; 3, set the trigger condition, it is to convert your callback function name into an address as a parameter in your function for system calls. Note: The callback function is called by the system, so it can be considered as a Windows system. Do not treat it as a member function of one of your classes.

The callback function belongs to the Windows system. I don't think the callback function belongs to the system. It should be said that the program will trigger this code by the system. This is the processing mechanism provided by windows, because the message is mastered by the system, and the system calls our program to process the message, which is more convenient. Otherwise, we have to try to read the message list again.

There are always some interfaces between software modules,
They can be divided into three types: Synchronous call, callback, and asynchronous call.

1. What is callback?

There are always some interfaces between software modules. In terms of calling methods, they can be divided into three types: Synchronous call, callback and asynchronous call. Synchronous call is a blocking call. The caller must wait for the execution of the other party to return the result. It is a one-way call. Callback is a two-way call mode, that is, the called party also calls the other party's interface when the interface is called. asynchronous calling is a mechanism similar to messages or events, but its caller is the opposite, when an interface service receives a message or an event, it proactively notifies the customer (that is, the customer's interface ). Callback and asynchronous call are closely related. Generally, callback is used to implement the registration of asynchronous messages and notifications of messages are implemented through asynchronous calls. Synchronous calling is the simplest of the three, and callback is often the basis of asynchronous calling. Therefore, we will focus on the implementation of callback mechanisms in different software architectures.

For different types of languages (such as structured and object languages), platforms (Win32, JDK), or architectures (such as CORBA, DCOM, and WebService ), in addition to the synchronous mode, the interaction between the customer and the service requires a certain asynchronous notification mechanism so that the service provider (or interface provider) can actively notify the customer in some situations, callback is the simplest way to implement Asynchronization.

For general structured languages, callback can be implemented through callback functions. A callback function is also a function or process, but it is a special function implemented by the caller for the caller.

In an object-oriented language, callback is implemented through an interface or abstract class. We turn the class implementing this interface into a callback class, and the object of the callback class into a callback object. For object languages such as C ++ or Object Pascal that are compatible with the process features, they not only provide callback objects, callback methods, and other features, but also support the callback function mechanism of the Process language.

The message mechanism on the Windows platform can also be seen as an application of callback. We use the interface provided by the system to register the message processing function (that is, the callback function) to receive and process messages. Because Windows APIs are built in C language, we can think of them as a special case of callback functions.

For the Distributed Component proxy system (CORBA), asynchronous processing involves multiple methods, such as Callback, event service, and notification service. Event Service and notification service are the standard services used by CORBA to process asynchronous messages. They are mainly responsible for message processing, distribution, and maintenance. Some simple asynchronous processing processes can be implemented through the callback mechanism.

2. Callback in process language (c)

2.1 function pointer

Callback is implemented by using the function pointer in the C language. The callback is implemented by passing the address of the callback function to the called function. Therefore, to implement callback, you must first define the function pointer. See the following example:

Void func (char * s); // function prototype
Void (* pfunc) (char *); // function pointer

We can see that the definition of a function is very similar to that of a function pointer.

In general, to simplify the definition of variables of the function pointer type and improve the readability of the program, we need to customize the function pointer type.

Typedef void (* PCB) (char *);

A callback function can be called by a program like a normal function, but it can be called a callback function only when it is passed as a parameter to the called function.

Example of the called function:

Void getcallback (PCB callback)
{
/* Do something */
}

When calling the above function, you need to implement a PCB type callback function by yourself:

Void fcallback (char * s)
{
/* Do something */
}

Then, you can directly pass fcallback as a variable to getcallback:

Getcallback (fcallback );

If different values are assigned to this parameter, the caller will call functions of different addresses. Assign values can occur at runtime, so that you can achieve dynamic binding.

2.2 parameter transfer rules

So far, we have only discussed function pointers and callbacks, but have not paid attention to the ansi c/C ++ compiler specifications. Many compilers have several call specifications. For example, in Visual C ++, you can add _ cdecl, _ stdcall, or _ Pascal before the function type to indicate its call specifications (default value: _ cdecl ). C ++ builder also supports the _ fastcall call specification. The call specification affects the given function name generated by the compiler, the sequence of parameter passing (from right to left or from left to right), and the responsibility for Stack cleaning (caller or called) and parameter transfer mechanism (stack, CPU register, etc ).

It is important to regard the call specification as part of the function type. Incompatible call specifications cannot be used to assign addresses to function pointers. For example:

// The called function uses int as the parameter and INT as the return value.
_ Stdcall int callee (INT );

// Call a function with the function pointer as the parameter
Void caller (_ cdecl int (* PTR) (INT ));

// Illegal operation of the called function address in P's Enterprise Image Storage
_ Cdecl int (* p) (INT) = callee; // Error

The pointer P and callee () types are incompatible because they have different call specifications. Therefore, the caller's address cannot be assigned to the pointer P, although the two have the same return value and parameter column.


2.3 Application Example

In many parts of the standard library functions in C language, callback functions are used to allow users to customize the processing process. Such as common quick sorting functions and binary search functions.

Quick Sort function prototype:

Void qsort (void * base, size_t nelem, size_t width, INT (_ userentry * fcmp) (const void *, const void *));

Binary Search function prototype:

Void * bsearch (const void * Key, const void * base, size_t nelem, size_t width, INT (_ userentry * fcmp) (const void *, const void *));

Fcmp is a callback function variable.

The following is a specific example:

# Include <stdio. h>
# Include <stdlib. h>

Int sort_function (const void * a, const void * B );
Int list [5] = {54, 21, 11, 67, 22 };

Int main (void)
{
Int X;

Qsort (void *) List, 5, sizeof (list [0]), sort_function );
For (x = 0; x <5; X ++)
Printf ("% in", list [x]);
Return 0;
}

Int sort_function (const void * a, const void * B)
{
Return * (int *) A-* (int *) B;
}

2.4 callback in object-oriented language (Delphi)

Like C ++, dephi retains its previous structural features while introducing the object-oriented mechanism to maintain compatibility with Pascal. Therefore, there are two different callback modes: a structured callback mode and an object-oriented interface mode.

2.4.1 callback function

Callback Function Type Definition:

Type
Tcalcfunc = function (A: integer; B: integer): integer;

Customize the function implementation according to the callback function format, as shown in figure

Function add (A: integer; B: integer): integer
Begin
Result: = A + B;
End;
Function Sub (A: integer; B: integer): integer
Begin
Result: = A-B;
End;

Use of callback

Function calc (calc: tcalcfunc; A: integer; B: integer): integer

Next, we can call these two functions in our program as needed.

C: = calc (add, a, B); // C = a + B
C: = calc (sub, a, B); // C = A-B

2.4.2 callback object

What is a callback object? In what scenarios is it used? First, let's compare it with the callback function. The callback function is a prototype that defines the function, and the function body is implemented by a third party in a dynamic application mode. To implement a callback function, we must know exactly the following points: the parameters required by the function and the type of values returned. Similarly, a callback object is an abstract class (that is, an interface) that defines the object interface but does not implement it ). To implement a callback object, we must know which methods should be implemented, which parameters are included in each method, and what values should be put back in this method.

Therefore, interfaces are used in the callback object application mode. An interface can be understood as a defined but not implemented class. It can only be implemented by other classes by means of inheritance. The interfaces in Delphi are similar to those in COM. All interfaces inherit from iinterface (equivalent to iunknow) and implement three basic methods: QueryInterface, _ addref, and _ release.

Define an Interface

Type ishape = interface (iinterface)
Procedure draw;
End

Implementation callback class

Type trect = Class (tobject, ishape)
Protected
Function QueryInterface (const IID: tguid; out OBJ): hresult; stdcall;
Function _ addref: integer; stdcall;
Function _ release: integer; stdcall;
Public
Procedure draw;
End;

Type tround = Class (tobject, ishape)
Protected
Function QueryInterface (const IID: tguid; out OBJ): hresult; stdcall;
Function _ addref: integer; stdcall;
Function _ release: integer; stdcall;
Public
Procedure draw;
End;

Use callback object

Procedure mydraw (shape: ishape );
VaR
Shape: ishape;
Begin
Shape. Draw;
End;

If the input object is trect, draw a rectangle; if it is tround, It is a circle. Users can also implement the ishape interface according to their own intentions to draw their own graphics:

Mydraw (trect. Create );
Mydraw (tround. Create );

2.4.3 callback Method

The callback method can be considered as a part of the callback object. Delphi uses the callback method to encapsulate Windows messages. In some cases, we do not need to implement the entire object according to the given requirements, but we only need to implement one of the methods. This is what we will use the callback method.

The callback method is defined as follows:

Tpolicyevent = procedure (Sender: tobject) of object;
Tmyevent = procedure (Sender: tobject; eventid: integer) of object;

Tpolicyevent is the most common callback method in Delphi. Many events of forms and controls, such as click events and close events, use tpolicyevent. Variables of the callback method are generally defined by event attributes, such as the definition of the event created by tcustomform:

Property oncreate: tpolicyevent read foncreate write foncreate stored isform;

We can customize the event processor by assigning values to the event attribute variable.

User-defined objects (objects containing callback methods ):

Type tcallback = Class
Procedure clickfunc (Sender: tobject );
End;
Procedure tcallback. clickfunc (Sender: tobject );
Begin
Showmessage ('the caller is clicked! ');
End;

Form object:

Type tcustomfrm = Class (tform)
Public
Procedure registerclickfunc (CB: Procedure (Sender: tobject) of object );
End;

Procedure tcustomfrm .. registerclickfunc (CB: tpolicyevent );
Begin
Self. onclick = CB;
End;

Usage:

VaR
FRM: tcustomfrm;
Begin
FRM: = tcustomfrm. Create (application );
FRM. registerclickfunc (tcallback. Create (). clickfunc );
End;

The callback function must have the keyword callback.The callback function must be a global or static function, and cannot be defined as a member function of a specific class?

2. The callback function is not directly called and executed by the developer (only the system interface API function is used as the starting point)

3. The callback function is usually passed to the system API as a parameter, which calls

4. The callback function may be called once by the system API or cyclically multiple times (sortitem is self-called)

In fact, there is another mechanism in Windows-message mechanism, which is also a good tool that can provide solutions for many practical problems.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.