A brief talk on javascript-callback function

Source: Internet
Author: User
Tags function prototype message queue win32

A callback function is a function that is called through a function pointer. If you pass the pointer (address) of the function as an argument to another function, when the pointer is used to invoke the function it points to, we say this is a callback function. The callback function is not called directly by the implementing party of the function, but is invoked by another party when a particular event or condition occurs, and is used to respond to the event or condition.

Chinese name

callback function

Foreign names

Callback Functions

Mean

Functions that are called through function pointers

Role

Respond to a specific event or condition

Mechanism to listen to speech

⑴ defines a callback function;

⑵ a party that provides a function implementation registers the function pointer of the callback function with the caller at initialization time;

⑶ when a particular event or condition occurs, the caller uses a function pointer to invoke the callback function to process the event.

Meaning listening to Speech

Because the caller can be separated from the callee, the caller does not care who the callee is. It only needs to know that there is a called function with a specific prototype and constraints. In short, a callback function allows a user to pass a pointer to a method that needs to be called as a parameter to a function so that the function can flexibly use different methods when dealing with similar events.

Want to know what the callback function does in practice? Let's say we're going to write a library that provides implementations of some sort algorithms (such as bubble sort, quick sort, shell sort, shake sort, and so on), in order to make the library more generic, do not want to embed the sorting logic in the function, and allow the user to implement the corresponding logic; What do you do when you can make libraries available for a variety of data types (int, float, string)? You can use a function pointer and make a callback.

Callbacks can be used for notification mechanisms. For example, sometimes to set a timer in a program, every time, a program will be notified, but the notification mechanism of the implementation of a program is not ignorant. Then a callback is required for a function pointer with a specific prototype to notify that a program event has occurred. In fact, the API uses a callback function, SetTimer (), to notify the timer. If no callback function is provided, it also sends a message to the program's message queue.

Another API function that uses a callback mechanism is Enumwindow (), which enumerates all the top-level windows on the screen, each of which can invoke a function provided by another program and pass the window's handlers. For example: If the callee returns a value, the iteration continues; Enumwindow () does not care where the callee is, nor does it care what the callee does with the handlers it passes, it only cares about the return value, because it will continue to execute or exit based on the return value.

In any case, the callback function is inherited from the C language. In C + +, the callback function should be used only when the interface is established with the C code or when dealing with an existing callback interface. In addition to the above, you should use virtual methods or functor (functor) instead of callback functions in C + +.

Achieve listening voice

Code implementation

The following creates a Sort.dll dynamic link library, which exports a type named Comparefunction--

Typedefint (__stdcall*comparefunction) (constbyte*,constbyte*)

It is the type of the callback function that is responsible for passing parameters to the corresponding specific element comparison function in the same parameter form. In addition, through it, two different sorting algorithms can be called and specific elements related to the comparison function, implementation and element type-independent ordering: Bubblesort () and Quicksort (), both methods use the same parameter prototype, but implemented a different sorting algorithm.

Voiddlldir__stdcallbubblesort (Byte*array,intsize,intelem_size,comparefunctioncmpfunc);

Voiddlldir__stdcallquicksort (Byte*array,intsize,intelem_size,comparefunctioncmpfunc);

The two functions accept the following parameters:

byte * Array: Pointer to an array of elements (any type).

int Size: The number of elements in the array.

int elem_size: The size, in bytes, of an element in an array.

· Comparefunction Cmpfunc: A pointer to a callback function with the above prototype.

Both of these functions sort the array, but each time you decide which of the two elements is in front, and the function has a callback function whose address is passed in as a parameter. For the writer, there is no need to mind where the function is implemented, or how it is implemented, all that is needed is the address of two elements for comparison, and returns one of the following values (both the writer and the user of the library must abide by this Convention):

-1: If the first element is smaller, it should precede the second element in the sorted array.

• 0: If two elements are equal, then their relative position is not important, and in the sorted array, it doesn't matter who is in front of them.

• 1: If the first element is large, it should be followed by a second element in the sorted array.

Based on the above conventions, the function Bubblesort () is implemented as follows, and Quicksort () is slightly more complex:

void Dlldir__stdcallbubblesort (Byte*array,intsize,intelem_size,cmpfunc)

{

for (inti=0;i<size;i++)

{

for (intj=0;j<size-i-1;j++)

{

Callback comparison function

if (1== (*cmpfunc) (array+j*elem_size,array+ (j+1) *elem_size))

{

Two-phase exchange of the elements of the comparison

byte* Temp=newbyte[elem_size];

memcpy (temp,array+j*elem_size,elem_size);

memcpy (array+j*elem_size,array+ (j+1) *elem_size,elem_size);

memcpy (array+ (j+1) *elem_size,temp,elem_size);

Delete[]temp;

}

}

}

}

Note: Because memcpy () is used in the implementation, the function is limited in terms of the type of data used.

For the consumer, there must be a callback function whose address is to be passed to the Bubblesort () function. Here are two simple examples, one comparing two integers and the other comparing two strings:

Int__stdcall compareints (CONSTBYTE*VELEM1,CONSTBYTE*VELEM2)

{

int elem1=* (int*) velem1;

int elem2=* (int*) velem2;

if (ELEM1<ELEM2)

return-1;

if (ELEM1>ELEM2)

RETURN1;

Return0;

}

int __stdcall comparestrings (constbyte*velem1,constbyte*velem2)

{

Const char* elem1= (char*) velem1;

Const char* elem2= (char*) velem2;

Return strcmp (ELEM1,ELEM2);

}

Here is another program that tests all of the above code, passing an array of 5 elements to Bubblesort () and quicksort (), as well as passing a pointer to the callback function. (Use the byte type to include the header file Windows.h, or

typedef UNSIGNEDCHAR BYTE;

int main (intargc,char*argv[])

{

int i;

int array[]={5432,4321,3210,2109,1098};

cout<< "beforesortingintswithbubblesort\n";

for (i=0;i<5;i++)

cout<<array[i]<< ' \ n ';

Bubblesort ((byte*) array,5,sizeof (array[0]), &compareints);

cout<< "afterthesorting\n";

for (i=0;i<5;i++)

cout<<array[i]<< ' \ n ';

const char str[5][10]={"Estella", "Danielle", "Crissy", "Bo", "Angie"};

cout<< "beforesortingstringswithquicksort\n";

for (i=0;i<5;i++)

cout<<str[i]<< ' \ n ';

Quicksort ((byte*) str,5,10,&comparestrings);

cout<< "afterthesorting\n";

for (i=0;i<5;i++)

cout<<str[i]<< ' \ n ';

Return0;

}

If you want to sort in descending order (large element first), you just need to modify the callback function's code, or use another callback function, so the flexibility of programming is quite large.

calling convention

In the above code, you can find __stdcall in the function prototype, because it starts with a double underscore, so it's a compiler-specific extension, and ultimately Microsoft's implementation. Any support for developing WIN32-based programs must support this extension or its equivalents. The function identified by __stdcall uses the standard calling convention, why is it called a standard convention, because all of the Win32 APIs (except for the individual accept mutable parameters) use it. The standard calling convention functions remove parameters from the stack before they are returned to the caller, which is also a standard specification for Pascal. However, in C + +, the calling convention is that the caller is responsible for cleaning up the stack instead of being called, and using the C + + calling convention for forcing the function can use __cdecl. In addition, variadic functions use the C + + calling convention.

The Windows operating system employs the standard calling convention (Pascal convention) because it reduces the volume of the code. This is important for early windows because it was running on a computer with only 640KB of memory.

If you don't like __stdcall, you can also use the callback macro, which is defined in Windef.h:

#define Callback__stdcallor

#define CALLBACKPASCAL//and Pascal was #defined into __stdcall here.

C + + method as a callback function

Since it is possible to write code in C + +, you might think of writing a callback function as a method in a class, but first take a look at the following code:

Class Ccallbacktester

{

Public

int callbackcompareints (CONSTBYTE*VELEM1,CONSTBYTE*VELEM2);

};

Bubblesort ((byte*) array,5,sizeof (array[0]), &ccallbacktester::compareints);

If you use the Microsoft compiler, you will get the following compilation error:

errorC2664: ' bubblesort ': Cannotconvertparameter4from ' int (__stdcallccallbacktester::*) (constunsignedchar*, constunsignedchar*) ' to ' Int (__stdcall*) (constunsignedchar*,constunsignedchar* ) ' Thereisnocontextinwhichthisconversionispossible

This is because the non-static member function has an extra parameter: the this pointer, which forces you to precede the member function with static.

A brief talk on javascript-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.