Callback Function)-C/C ++

Source: Internet
Author: User

The Calling mechanism has been widely used since the Assembly era: Prepare a piece of ready-made code, the caller can jump to the starting address of the code segment at any time, and then return the subsequent address when the jump is completed. For this reason, the CPU has prepared ready-made call commands. During the call, the stack can be pressed to protect the scene. After the call is completed, the on-site address will pop up from the stack for automatic return. It was a wonderful invention to use stack to protect the scene. It made it possible for callers and the called to not know each other, so they had the functions and components that made our programmers so easy and pleasant. If we select the invention that has the greatest impact on humans, the author calls the stack after the fire and the wheel.
In this case, the call mechanism is not perfect. The callback function is an example. Functions and others are delicious meals for callers. The cookers should be familiar with diners, but this is not the case. For example, you can write a quick sort function for others to call. It must contain a comparison value. The trouble is: at this time, I do not know what kind of data to be compared-integer, floating point, String? Therefore, we had to create a different sorting function for each type of data. A more common method is to list a callback function address in the function parameters and notify the Caller: You need to prepare a comparison function, which contains two pointer-class parameters, the function needs to compare the data size indicated by the two pointers, and the comparison result is described by the return value of the function. The sorting function compares the size by using the function provided by the caller. By passing parameters through the pointer, the data type can be completely ignored. The caller calls the caller's function (which is enough to bite) and calls it a callback ). (Sort function in STL)
The callback function makes the program structure messy. There are many callback functions in the Windows API function set. Despite detailed descriptions, it still makes beginners confused. I'm afraid this is also helpless. Whatever kind of things, one-way description in a tree structure is more comfortable after all. If a family's grandchildren are grandparents, I'm afraid no one can understand their clues. However, the complexity of data processing often requires a mesh structure. Non-simple customer/Server relationships can be exhausted.
Windows also contains another broader callback mechanism, namely, message mechanism. A message is a basic control method of windows. It is a disguised function call that has nothing to do with function call. The purpose of sending a message is to notify the recipient to run a pre-prepared code, which is equivalent to calling a function. The wparam and lparam parameters attached to a message are equivalent to the function parameters, but they are more common than common parameters. Applications can actively send messages. In more cases, they are waiting for Windows to send messages. Once a message enters the message queue, you can check the messages you are interested in and jump to execute the corresponding message processing code. The operating system serves applications and is called by applications. Once the application is started, it will wait for the operating system to call. This is also a callback, or a generalized callback. In fact, such callbacks can also be formed between applications. If process B receives a message from process a, starts a piece of code, and sends a message to process a, this forms a callback. This kind of callback is relatively concealed, which may lead to recursive calls. If the termination condition is missing, it will loop until the program is broken down. It is interesting to write this recursive call and set the termination conditions. However, such a program structure is too concealed unless necessary.
I remembered two callbacks when I wrote TTS.
Messages can also form narrow callbacks. In the preceding sorting function example, you can replace the callback function address with the window handle. In this way, when the data size is relatively large, instead of calling the callback function, the API function sendmessage is used to send messages to the specified window. The recipient is responsible for comparing the data size and passing the comparison result to the sender through the return value of the message itself. The implemented functions are no different from the callback functions. Of course, in this example, the message is purely a snake, but the program is very slow. However, this is not always the case in other cases. In particular, sending messages is a good option when asynchronous calls are required. If the callback function contains low-speed processing such as file processing and the caller is not allowed, you need to change the synchronous call to asynchronous call to start a separate thread and then immediately execute the subsequent code, other things let the thread do it slowly. One alternative is to use the postmessage API function to send an asynchronous message and then immediately execute subsequent code. This is much easier and safer than self-built threads.
Now we are living in the object age. As long as it is related to programming, no matter what happens, it cannot be separated from the object. But the object does not eliminate the callback. Instead, it carries forward and gets everything, but most of them appear as events and are embedded in a structure, which is more orthodox, it is easier to accept. To use a component, an application must first understand the attributes, methods, and events of the component, assign values to the component attributes, and call appropriate component methods when appropriate, you also need to write processing routines for the event to be called by the component code. What is an event? It is just an address pointing to the event routine, which is no different from the callback function address.

However, this callback method is much better than traditional callback functions. First, it turns uncomfortable callback functions into a natural processing routine, making programmers feel comfortable. Furthermore, the address is a dangerous thing. If it is used, it can accelerate the program. If it is not used, it is a trap everywhere and the program will crash at any time. Modern programming methods always try to hide addresses (such as VB and Java) at the cost of reducing program efficiency. The event routine does not allow programmers to directly manipulate the address, but does not slow down the program. What's even better is that this change is a new design concept that makes it easy to get attacked, and it forces us to change our clothes and study carefully, admired so far. Just by chance, quietly thinking, I found that there was only a bottle of old wine, so this discussion made them laugh. The event driver is designed around the Message Base. An event occurs with a lot of messages.

I understand that the "callback mechanism" refers to window calling a specified function while executing an API function. We can simulate:
Assuming that the MS provides a function called enumfont that gets all the fonts, assuming its implementation is
Enumfont ()
{
While (F = findnextfont ())! = NULL)
{
Printf ("fontname:" + F. Name );
}
}
In this way, all font names are displayed cyclically. However, developers may have additional use for the font information, so how can they make the developer use the information:
Enumfont (void * userfunc)
{
While (F = findnextfont ())! = NULL)
{
Printf ("fontname:" + F. Name );
If (userfunc! = NULL) userfunc (f );
}
}
Assume that userfunc is a function void F (fontobject font). In this way, you only need to define one function:
Void myfunc (fontobject font)
{
Listctrl. addstring (font. Name );
}

You can use enumfont (myfunc) to add all the font information to a list box. So we call myfunc a callback function, that is, a function called by a system function. Therefore, we can draw a conclusion:
1. The callback function is defined by the developer according to a certain prototype.
2. The callback function is not directly called and executed by developers.
3. The callback function is usually passed to the system API as a parameter and called by this API.
4. The callback function may be called once by the system API or cyclically multiple times.

For example, the int enumfontfamilies (
HDC, // handle to Device Control
Lpctstr lpszfamily, // pointer to family-name string
Fontenumproc lpenumfontfamproc, // pointer to callback function
Lparam // pointer to application-supplied data
);
The fontenumproc callback is a callback function defined in the format of int callback enumfontfamproc (enumlogfont far * lpelf, newtextmetric far * lpntm, int fonttype, lparam.

The callback function is mainly used for some time-consuming operations or events that do not know when the response will occur. The callback function provides an asynchronous mechanism, which improves the efficiency compared with synchronous execution. examples of the former include writefileex and readfileex. The last parameter of the function is the pointer of a callback function. After writefileex is called in the program, it is returned directly. You can continue other work, after the system completes reading and writing, it notifies the program to handle the problem. the latter example is another use of the Event Callback Function in windows. It is used for some enumeration functions, such as enumdisplaymodes. Every time a supported display mode is found, the callback function is notified, it is handled by the callback function because enumdisplaymodes does not know how to handle it. yes. You can provide callback functions and custom system functions. In this way, different users provide different callback functions, so that the system has different functions. this is the so-called plugin. when a callback function is called (usually an API function ), The address of the callback function. The callback function is called using the passed address when needed. You can use this opportunity to process messages or complete certain operations in the callback function. How to define a callback function is related to the specific API function used. The parameters and return values of the callback function are generally described in the help section.
========================================================== ======================================

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.