标签:
什么是回调函数?
回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。
实现机制:
1
|
typedefint(__stdcall*CompareFunction)(constbyte*,constbyte*) |
1
2
|
voidDLLDIR__stdcallBubblesort(byte*array,intsize,intelem_size,CompareFunctioncmpFunc); voidDLLDIR__stdcallQuicksort(byte*array,intsize,intelem_size,CompareFunctioncmpFunc); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
void DLLDIR__stdcallBubblesort(byte*array,intsize,intelem_size,cmpFunc) { for (inti=0;i<size;i++) { for (intj=0;j<size-i-1;j++) { //回调比较函数 if (1==(*cmpFunc)(array+j*elem_size,array+(j+1)*elem_size)) { //两个相比较的元素相交换 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; } } } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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); } |
1
|
typedef unsignedchar byte; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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; } |
1
2
|
#define CALLBACK__stdcallor #define CALLBACKPASCAL//而PASCAL在此被#defined成__stdcall |
1
2
3
4
5
6
|
class CCallbackTester { public : int CALLBACKCompareInts(constbyte*velem1,constbyte*velem2); }; Bubblesort((byte*)array,5, sizeof (array[0]),&CCallbackTester::CompareInts); |
1
|
error C2664 :’ Bubblesort ’:cannotconvertparameter4from’int(__stdcall CCallbackTester ::*)(constunsignedchar*,constunsignedchar*)’to’int(__stdcall*)(constunsignedchar*,constunsignedchar*)’ Thereisnocontextinwhichthisconversionispossible |
标签:
原文地址:http://blog.csdn.net/fanyunda1988/article/details/51499678