Callback functions in the C language (Callback function)

Source: Internet
Author: User

1 Definitions and use cases

A callback function is a function that a user defines a function, implements the program content of the function, and then passes the function (the entry address) as a parameter to another (or system) function, which is called by another (or system) function at run time. Functions are implemented by you, but are called by other (or system) functions at run time through parameter passing, which is called a callback function. Simply put, it is the function that you implement when you run the function of someone else.

This design allows the underlying code to invoke subroutines (shown in 1-1) that are defined at the top level. The callback function in C language is mainly implemented by function pointers.

Figure 1-1 callback function in the software system call result

Callbacks are very versatile: [1]

For example, suppose you have a function that reads a configuration file and sets the appropriate options for the file content. If these options are marked by a hash value (hash function), allowing the function to accept a callback will make the program more flexible: The caller of the function can use the desired hashing algorithm, which is implemented by a callback function that transforms the option name into a hash value; Callbacks allow function callers to adjust the behavior of the original function at run time .

Another use of callbacks is to handle semaphores. For example, a POSIX program may not want to terminate immediately when receiving a sigterm signal, and to ensure that everything works well, the program can register the cleanup function as a callback corresponding to the sigterm signal.

Callbacks can also be used to control whether a function acts as: Xlib allows a custom predicate (nspredicate) to determine whether the program wants to handle a particular event.

#include <iostream>#include<string>using namespaceStd;typedefvoid(*FP) (Char* s);//struct represents a function pointervoidF1 (Char* s) {cout<<s;}voidF2 (Char* s) {cout<<s;}voidF3 (Char* s) {cout<<s;}intMainintargcChar*argv[]) {    intFuncselector=0;//define an integer to control the function to be executed    void* A[]={F1,F2,F3};//defines an array of pointers, where a is a normal pointera[0]("Hello world!\n");//compile error, pointer array cannot call function by subscriptFP f[]={F1,F2,F3};//defines an array of function pointers, where f is a function pointer        /*Handle of Funselector*/       //This is used to process funselector, to control the function to be executedF[funselector] ("Hello world!\n");//correctly, an array of function pointers can be used for indirect invocation of functions        return 0;} 

In the above example, some of the functions of the callback function are mentioned. Here F1,F2,F3 represents three functions with different functions (for example: F1 to achieve the maximum output, F2 to achieve the average output, F3 to achieve the minimum output). Summarize some of the benefits of the callback function:

Using Funcselector as the symbol, selecting the function to be executed is very convenient to control the process and operation of the function.

F1,F2,F3 three specific functions are modular and easy for designers to maintain and modify. As shown in 1-1, the software library in many systems is fully encapsulated so that developers can only modify function functions with callback functions.

The analytic function is clearer, and the callback function is used extensively in lwIP, and the developer can analyze the system structure based on the call process of the callback function.

2 Structure Analysis

The main structure of the callback function consists of three parts: the main function, the calling function, and the modulated function (1-1). In C, the called function is usually in the form of a function pointer (which points to the entry address of the corresponding function).

This gives the simplest structure of the callback function and parses the relevant data structure.

//Defining callback FunctionsvoidPrintftext () {printf ("Hello world!\n");}//defines the "calling function" that implements the callback functionvoidCallprintftext (void(*callfuct) ()) {callfuct ();}//Implementing a function callbackintMainintargcChar*argv[])    {Callprintftext (Printftext); return 0;}

The calling function passes Void (*callfuct) (void ) to its function, which is the entry address of a void callfuct (void) function, that is, the PC pointer can be moved to that address to perform void The callfuct (void) function can be understood by analogy arrays.

In the implementation function call, the function calls the "Call function", where further calls are called functions. This method provides a flexible interface to the consumer rather than to the developer by invoking the "tuned function" directly compared to the main function. In addition, function portals can be set up like variables to provide flexibility for developers as well.

3 Example Analysis

Here is an example of a more complex callback function used in a LWIP:

voidHttpd_init (void){    structTCP_PCB *PCB; PCB=tcp_new (); Tcp_bind (Pcb,ip_addr_any, the); PCB=Tcp_listen (PCB);        Tcp_accept (PCB, http_accept); }voidTcp_accept (structTCP_PCB * PCB, err_t (* accept) (void*arg,structTCP_PCB *NEWPCB, err_t err))Staticerr_t Http_accept (void*arg,structTCP_PCB *PCB, err_t err) {    /*set the Prio of callback function, important*/Tcp_setprio (PCB, tcp_prio_min);    TCP_RECV (PCB, HTTP_RECV); returnERR_OK; }    voidTcp_recv (structTCP_PCB * PCB, err_t (* recv) (void* ARG,structTCP_PCB * TPCB,structPBUF *p, err_t err))Staticerr_t Http_recv (void*arg,structTCP_PCB * PCB,structPBUF *p, err_t err) {    /*HTML handler by user ' s definition*/    /*Use tcp_write (PCB, message, sizeof message, 0) to send message*/}

Here we call the two-level callback function, which is interesting to see the raw part of LWIP.

4 references

[1] Https://zh.wikipedia.org/wiki/%E5%9B%9E%E8%B0%83%E5%87%BD%E6%95%B0

[2] Http://partow.net/programming/templatecallback/index.html

[3] Http://www.partow.net/programming/hashfunctions/index.html

[4] http://blog.csdn.net/callmeback/article/details/4242260

[5] Http://www.cnblogs.com/chenyuming507950417/archive/2012/01/02/2310114.html

Callback functions in the C language (Callback function)

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.