编写C/C++ 程序时,才开始接触回调函数的使用可能回弄糊涂。本篇以C为例子,简要说一下回调函数的使用。
C/C++中回调,有点类此C#中的事件等。一般在写库程序和主调程序时使用,为了在主调程序中获取库文件中的数据一般采用回调函数的方式。设计回调函数时,主要考虑两类参数,一则是库返还给用户的数据参数,另则是用户自己的数据。下面写个简单代码,说明。so文件包含file.c file.h文件,主程序main.c文件。
file.h
#ifndef FILE_H_
#define FILE_H_
typedef void (*CALLBACKFUN)(void*pdata,size_t len,void*pUser);
//开始服务
void ServerStart(CALLBACKFUN callfun,void *pUser);
//停止服务
void ServerStop();
#endif
file.c
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include "file.h"
_Bool startflag=false;
void ServerStart(CALLBACKFUN callfun,void *pUser){
char buff[64];
memset(buff,0,sizeof(buff));
startflag=true;
while (startflag) {
if(gets(buff))
{
callfun(buff,strlen(buff),pUser);
}
}
}
void ServerStop()
{
startflag=false;
}
main.c
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include "file.h"
void mycallback(void*pdata,size_t len,void*pUser)
{
int id=*(int*)pUser;
printf("current ID is:%d\nreceive data is:%s,data len is %u\n",id,(char*)pdata,len);
}
void *threadfun(void *p)
{
int id=100;
ServerStart(mycallback,&id);
}
int main()
{
pthread_t pth;
pthread_create(&pth,NULL,threadfun,NULL);
printf("10S后停止服务\n");
sleep(10);
ServerStop();
}