Callback functions and class members in C + + as callback functions __jquery

Source: Internet
Author: User

One, callback function

When looking at LWIP, see Using callback function, look at a foreigner company OPC source code, see Use callback function. Look at some of my domestic code (my company software, etc.) is useless. So, I have a lot of curiosity about the callback function. I used to use the callback function when I wrote the VC program, but I didn't use it in C language. Recently, see a lot of classical code abroad widely used in the callback function (LWIP, the OPC program of two companies, etc.), are the C language to achieve, rather than VC Windows program for others to achieve their own use of the kind.

To understand the mystery of this function, first ask three questions:

1. What the callback function is.

2. callback function How to develop, how to use.

3. The function of the callback function, should be used under what circumstances.

To learn with questions, with a purpose. Oh, personal experience.

Open baidu.com, google.cn search for a lot of information, as follows:

By the way, one of the gentleman's signature I admire: 1 Live Well, because we will die for a long time. 2 5,000 years of civilization 200 years of helplessness

First question:

*******************************************************************************

In fact, the callback is a function of the function of the pointer to call the process.

Why do you use a callback? For example, I want to write a sub module for you to receive remote socket Send command. When I receive the command, I need to call the function of your main module to handle it accordingly. But I don't know which function you're going to use to handle this command, and I don't know what your main module is. cp   P or. h, or, I don't care what you do with it in the main module, or what functions you use to handle it ... What to do?

Use callback!

--lone Wolf

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.

--An expert

The callback function is written by yourself. You need to call another function, and one of the arguments to this function is the name of your callback function. This way, when necessary, the system invokes the callback function that you write, so you can do what you want to do in the callback function.

--Green leaves

Http://hi.baidu.com/zhuyipeng/blog/item/863fefdb7c736c63d1164eec.html is a relatively good article.

What is a callback function?
A callback function is a function that an application provides to a Windows system DLL or other DLL, typically used to intercept messages, get system information, or handle asynchronous events. The application tells the DLL the address pointer of the callback function, and the DLL calls the function when it is appropriate. The callback function must conform to the predetermined parameter format and delivery method, or the DLL's invocation of it can cause the program or system to crash. In general, the callback function takes the standard WINDOWSAPI invocation, that is, the __stdcall, of course, the DLL can define the invocation method on its own, but the client program must follow the same rules. In the __stdcall mode, the function's arguments are pressed from right to left in the stack, except explicitly indicating that the pointer or reference, the parameters are passed by value, the function returns before returning the parameter from the stack.
Understand the callback function!

--jufengfeng

Function pointers provide the concept of callback functions.

--newty.de

*******************************************************************************

After reading so much information, I only summed up the definition of each one in one sentence: The callback function is a use of the function pointer.

In part of the data, a lot of discussion about how the callback function is called, who is called, there are many graphics, I do not see the nature of the problem.

Second question:

*********************************************************************

I implemented a very simple callback function.

#include <stdio.h>

void printwelcome (int len)

{

printf ("Welcome welcome--%d/n", Len);

}

void Printgoodbye (int len)

{

printf ("A visitor to the visitor-%d/n", Len);

}

void callback (int times, void (* print) (int))

{

int i;

for (i = 0; I < times; ++i)

{

print (i);

}

printf ("N/a) I do not know whether you are welcome or see a visitor!/n/n");

}

void Main (void)

{

Callback (Printwelcome);

Callback (Printgoodbye);

Printwelcome (5);

}

*******************************************************************************

The above code is not called by any system function, which means that those things are just the eyes of the lost man in the scattered soil. Also have the object programming, with class to encapsulation is also to deceive, don't be puzzled by appearance.

Third question:

*********************************************************************

STL people know that in the STL many algorithms and procedures are used to callback functions, which implements a strategy. As long as any functions and calculations that meet my criteria can be used in my formula. You can implement a variety of callback functions, as long as they fit in my format.

As far as the above program is concerned, you can work as long as the function format conforms to the cllback of the second parameter, whether you cook for someone or make a bed. This is the role of the callback, leaving the callback implementation to others.

This is a usage.

A friend explained the callback mechanism with a layered concept: The callback function is B, the main function and the print* function are layer A, the layer a calls the B-level callback function Callmeback, and the B-level callback function calls the implementation function print* of layer a. Plainly, the B-layer is an interface.

This is my understanding. Over.


Let class member function as callback function in C + +

Note: Use with Tr1::function object, can obtain better effect, see http://blog.csdn.net/this_capslock/article/details/38564719


Callback functions are based on the C programming Windows SDK Technology, not for C + +, programmers can be a C function directly as a callback function, but if you try to directly use C + + member functions as a callback function will have errors, or even compile can not pass.

Ordinary C + + member functions imply a pass-through function as an argument, that is, the "This" pointer, which is implemented by passing a pointer to itself to its member function, thereby enabling the program function to access the data members of C + +. This also makes sense of why multiple instances of a C + + class can share member functions but do have different data members. Because the this pointer is used to install a member function of type callback as a callback function, a callback function installation fails because the implied this pointer causes the number of function parameters to not match.

In theory, a member function of a C + + class cannot be used as a callback function. But when we use C + + programming, we always want to implement its function in the class, that is, to maintain the encapsulation, if the callback function to write a common function has a lot of inconvenience. After searching and researching on the Internet, several ingenious methods have been found to make the class member function used as a callback function.

This uses the Linux C + + thread to create the function Pthread_create example, its prototype is as follows:

[CPP] view plain copy print? int pthread_create (pthread_t *restrict TIDP, const pthread_attr_t *restrict attr, void* (*START_RTN) (void*), void *res Trict Arg);

The first parameter is a pointer to the thread identifier. The second parameter is used to set the thread properties. The third parameter is the starting address of the thread's running function, which is the callback function. The last parameter is the parameter of the running function.
Here we only focus on the third parameter Start_run, which is a function pointer to a function that takes void* as the parameter and returns a value of void*, which is used as a thread's callback function, and executes the code of the function after the thread starts.
Method One: The callback function is a normal function, but performing member functions in the body of the function see the following code:[CPP]  View plain  copy  print? class myclass   {       pthread_t TID;   Public:        void func ()        {            //Child Thread Execution code        }           bool startthread ()        {//boot sub-thread            int ret = pthread_create ( &TID   NULL , callback , this );            if ( ret != 0 )                 return false;           else   

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.