C + + callback function usage

Source: Internet
Author: User
Tags comparison message queue prepare sort thread

A callback function

We often use the callback function in C + + design to make some applications (such as timer event callback processing, using callback function to record the progress of an operation, etc.) become very convenient and logical, then its intrinsic mechanism, how to define it? How does it differ from other functions, such as the hook function?

Using a callback function is actually a function (usually an API function) that passes the address of one of its functions (which is the callback function) as an argument to that function.

And that function, when needed, invokes the callback function with the address passed, at which point you can use this opportunity to process the message in the callback function or to complete a certain operation. As to how to define a callback function, it is related to the specific API function used, and there is usually a description of the parameter and return value of the callback function in the Help. C + + generally requires a callback (equivalent to far PASCAL) before the callback function, which is primarily a description of how the function is invoked.

As for the hook function, it's just a special case of the callback function. The callback function used in conjunction with the SetWindowsHookEx function is customarily called the hook function. Others have used VirtualQueryEx to install functions called hook functions, but this term is not very popular.

It can also be easier to understand: The callback function is like an interrupt handler, which is invoked automatically when it meets the criteria you set. To do this, you need to do three things:

1. Declaration;

2. Definition;

3. Set the trigger condition, which translates your callback function name into an address as an argument in your function to facilitate system invocation.

Notice and define that the callback function is called by the system, so you can think of it as belonging to the Windows system, not as a member function of one of your classes.

Two callback functions, messages, and event routines

The call (calling) mechanism has been used extensively since the Assembly age: Prepare a piece of ready-made code, the caller can jump to the beginning of this code at any time, after execution and then return to the subsequent address of the jump. The CPU prepares a ready-made call instruction for this purpose, when invoked, it can protect the scene by pressing the Stack, and pops the field address from the stack after the call is completed so that it returns automatically. It was a wonderful invention to borrow the stack to protect the scene, which enabled the caller and the callee to meet each other, so that later functions and artifacts were available.

This invocation mechanism is not perfect. The callback function is one example. Functions such as this is a meal prepared for the caller, the cook should be familiar with the diners, but the truth is not the case. For example, write a quick sort function for others to call, which must contain the comparison size. Trouble: At this point, I do not know what kind of data to compare--integers, floating-point numbers, strings? So I had to make a different sort function for each type of data. A more common approach is to list a callback function in the function parameter and notify the caller: you need to prepare a comparison function, which contains two pointer class parameters, which compare the size of the data referred to by the two pointers and indicate the comparison results by the function return value. The sort function takes the function provided by this caller to compare the size, and the pointer passes the parameter, regardless of the data type being compared. The callee calls the caller's function (enough Shang) to call it a callback (callback).

Callback functions cause a lot of confusion in the program structure. There are a number of callback functions in the Windows API function set, which are confused for beginners, despite exhaustive instructions. I am afraid this is also a helpless move.

No matter what kind of thing, can be described in a tree-shaped one-way description after all it makes people comfortable. If a family of grandchildren is a grandparent, I am afraid no one can clarify the clue. But the complexity of data processing often needs to form a network structure, not simple client/server relationship can be exhausted.

The Windows system also contains a more extensive callback mechanism, the message mechanism. The message is the basic control of Windows, at first glance unrelated to function calls, in fact, is a disguised function call. The purpose of sending a message is to notify Deceptions to run a piece of prepared code, which is equivalent to calling a function. The WParam and LParam that are included with the message are equivalent to the parameters of the function, but are more general than normal parameters. Applications can actively send messages, and more often wait for Windows to send messages. Once the message enters the owning message queue, it checks for those interested and jumps to execute the corresponding message processing code. The operating system is originally for application services and is invoked by the application. Once the application starts, it waits for the call of the operating system to turn. This is clearly a callback, or a generalized callback. In fact, this callback can also be formed between applications. If process B receives a message from process A, it initiates a piece of code, which sends a message to process a, which forms a callback. This callback is relatively covert, bad will make a recursive call, if the lack of termination conditions, will cycle unceasingly, until the program is broken down. It would be interesting to deliberately write this recursive call and set the termination conditions. But this kind of program structure is too covert, unless very necessary, still do not need to be good.

The use of messages can also constitute a narrow callback. As an example of the sort function above, you can change the callback function address into a window handle. So, when you need to compare the data size, instead of calling the callback function, you borrow the API function SendMessage to send the message to the specified window. The receiving party is responsible for comparing the data size, passing the comparison result to the message sender by the return value of the message itself. The functionality implemented is not different from the callback function. Of course, in this case, the message is pure painting snake tim feet, but the procedure is very slow. This is not always the case in other cases, especially when asynchronous calls are required, and sending messages is a good choice. If the callback function contains low speed processing such as file processing, the caller cannot, and needs to change the synchronous call to an asynchronous call, to start a separate thread, and then immediately execute the subsequent code, and the rest of the thread is slow to do so. An alternative is to borrow the API function PostMessage to send an asynchronous message, and then execute the subsequent code immediately. This is much easier and safer than getting a thread.

Now we are living in an object era. As long as it's about programming, you can't do anything without object. But object did not eliminate the callback, but it carried it forward, making it everywhere, but mostly in the identity of events (event), embedded in a certain structure, appear more orthodox, more easily accepted. To use a component, an application must first understand the properties, methods, and events of the component, assign a value to the component attribute, call the appropriate component method at the appropriate time, and write a process routine for the event to be invoked by the component code. What is an event? It's just an address to an event routine, no different from the callback function address.

However, this type of callback is much smarter than the traditional callback function. First, it turns the uncomfortable callback function into a natural processing routine that makes the programmer feel good. Moreover, the address is a dangerous thing, with good can make the program speed up, with bad everywhere is a trap, the program will collapse at any time. Modern programming is always the idea of hiding the address (hidden more thoroughly such as VB and Java), the cost is to reduce the efficiency of the program. Event Routines (? Allows programmers to not directly manipulate addresses, but does not slow down the program.

(routines seem to be the process of Taiwanese translation.) )

Three subtle metaphors: The callback function is a bit like the BP machine you carry with you: tell someone the number and call you when it has something to do.

Callbacks are used for layer collaboration, and the upper layer installs the function on the lower level, this function is the callback, and the lower layer triggers the callback under certain conditions, for example as a driver, is a bottom, he receives a data, in addition to complete this layer of processing work, but also will be a callback, the data to the upper layer of application to do further processing, This is common in layered data communications. In fact, callbacks and APIs are very close, and their commonalities are functions that are called across layers. The difference is that the API is a low-level call to the high-level, which is generally known to the upper level, and the callback is the opposite, he is the upper level provided to the bottom of the call, for low-level he is unknown, must be installed by the high-level, this installation function is actually a low-level provided API, The lower layer does not know the name of the callback after installation, but it saves the callback with a function pointer that simply references the function pointer and the associated parameter pointer when it needs to be invoked. In fact: The callback is the function written at the high level, the low-level through a function pointer to save the function, in an event triggered, low-level through the function pointer to call the high-level function.

Related Article

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.