#include <time.h>
#include <iostream>
using namespace std;
int getTime()
{
return clock() / CLOCKS_PER_SEC;
}
void debug(int num)//回调函数,这个函数模拟处理windows的不同消息,相当于win32的窗口过程处理函数windowProc
{
switch (num)
{
case 1:
cout << "this is the first one" << endl;
break;
case 2:
cout << "this is the second one" << endl;
break;
case 3:
cout << "this is the third one" << endl;
break;
default:
cout << "this is the default one" << endl;
break;
}
}
typedef void(*PFCALLBACK)(int); //PFCALLBACK是类型名
int start(PFCALLBACK f)//f是变量名,函数指针
{
srand(time(0));
int lastTime = 0;
while (true)
{
int now = getTime();
if (now - lastTime ==1)//每隔一秒
{
int num = rand() % 10;//产生0到10之间的数据
f(num); //调用回调函数
lastTime = now;
}
}
}
//为什么需要回调函数?
//第一,start函数本身可能不是你自己写的,已经封装成了dll,根本无法在start函数内部调用你的debug()函数
//第二,采用回调函数可以使你的dll库更具有通用性,使用start函数的每个人可以写自己的debug函数
int main()
{
start(debug);
}
//模拟window系统调用回调函数的过程
c语言模拟window系统调用回调函数的过程
最新推荐文章于 2024-03-30 18:13:37 发布