https://www.sharetechnote.com/html/C_callback.html
回调/函数指针
回调是一种将函数(而不是值)作为参数传递给另一个函数的机制。大多数有一点编程经验的读者都创建过函数。但是你创建的几乎所有(或每一个)函数可能都是没有任何参数的函数(或称为void参数的函数),或者是带有值参数的函数(例如,以int、char、char*、struct等形式的参数),你可能不知道可以将函数作为参数传递。如果你不自己尝试,很难理解它是什么。只需尝试这里列举的几个例子。
示例
无返回值的回调函数(void返回值)
有返回值的回调函数
typedef回调函数
回调函数数组
Example 1 > Callback function with no return (void return)
#include <stdio.h>
void PrintMsg()
{
printf("Hello World");
}
// This function takes in a function as an argument
void RunCallBack(void (*ptrFunc)())
{
ptrFunc();
}
int main()
{
// The address of the function PrintMsg() is passed as an argument to RunCallBack()
RunCallBack(&PrintMsg);
}
Result :----------------------------------
Hello World
Example 2 > Callback function with return
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* PrintMsg()
{
return "Hello World";
}
// This function takes in a function as an argument
void RunCallBack(char* (*ptrFunc)())
{
char* msg;
msg = (char *)malloc(255);
strcpy(msg,ptrFunc());
printf("%s",msg);
}
int main()
{
// The address of the function PrintMsg() is passed as an argument to RunCallBack()
RunCallBack(&PrintMsg);
}
Result :----------------------------------
Hello World
Example 3 > typedef callback function
#include <stdio.h>
typedef void (*callback)(); // now the void function point can be called as a new type called 'callback'
void PrintMsg()
{
printf("Hello World");
}
void RunCallBack(callback ptrFunc)
{
ptrFunc();
}
int main()
{
RunCallBack(&PrintMsg);
}
Result :-----------------------
Hello World
Example 4 > Array of Callback function
#include <stdio.h>
#include <time.h>
typedef void (*callback)();
void PrintMsg()
{
printf("Hello World\n");
}
void PrintTime()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s\n", asctime (timeinfo) );
}
void RunCallBack()
{
int i;
callback aryCallback[2] = {PrintMsg, PrintTime};
callback ptrFunc;
for( i = 0; i < 2; i++ ) {
ptrFunc = aryCallback[i];
ptrFunc();
}
}
int main()
{
RunCallBack();
}
475

被折叠的 条评论
为什么被折叠?



