回调机制的简单实现
a simple implement of callback mechanism
上班的时候一个同事坐在我旁边看我review代码,看到了我的callback函数,就开始问我这是什么东西,我很奇怪,丫也工作了好几年了,怎么还问我这种问题,给他解释了老半天。然后他要我给他将怎么样实现的,能不能给他写一个范例。给磨得没有办法,就信手写了一下。
/* --------------------------------------------------------------
* FILE NAME : Callback.c
* AUTHOR : sAm yOuNg
* Creation Date : 2005/12/05
* DESCRIPTION : a demo of callback mechanism *
* --------------------------------------------------------------
*/
//define register table struct
typedef struct tagCallbackTable
{
unsigned int nEvent;
void (*callbackfunc)(char *buffer,unsigned int len);
}STRUCT_REG_TABLE,*PSTRUCT_REG_TABLE;
#define MaxEvent 12
//define the msg struct
typedef struct tagMsgHeader
{
int nIdx;
int nEvent;
int nLen;
}STRUCT_MSG_HEADER,*PSTRUCT_MSG_HEADER;
//define a global variable of table array
STRUCT_REG_TABLE g_RegTable[MaxEvent];
//phase 1,init the reg table
memset(g_RegTable,0,sizeof(STRUCT_REG_TABLE)*(MaxEvent));
//phase 2, receive the register event
void RegisterEvent(int msgEvent,void (*callback_func)(char *buffer,int len))
{
//validate the register params. //write to register table
g_RegTable[msgEvent].nEvent = msgEvent;
g_RegTable[msgEvent].callbackfunc = callback_func;
}
//phase 3, process message and registered table.
void mainTableProcess()
{
int msgEvent=0;
int len=0;
PSTRUCT_MSG_HEADER lpMsgHeader = NULL;
//get msg and allocate buffer
while(getMsg(lpMsgHeader))
{
msgEvent=lpMsgHeader->nEvent;
len=lpMsgHeader->nLen;
for(int i=0;i<=MaxEvent;i++)
{
if( (g_RegTable[i].nEvent == msgEvent) )
{
//call the callback function registered
g_RegTable[i].callbackfunc((char*)lpMsgHeader,len);
}
}
}
}
//define a callback function and register it
//define events
#define EVENT_1 1
#define EVENT_2 2
#define EVENT_3 3
void test_callback_1(char *pptr,uint len)
{
PSTRUCT_MSG_HEADER lpMsgHeader = NULL;
//process the msg buffer
return 0;
}
void test_callback_2(char *pptr,uint len)
{
PSTRUCT_MSG_HEADER lpMsgHeader = NULL;
//process the msg buffer
return 0;
}
//init system and register event and callback function
void sysInit()
{
//init sys
//.................
//register event and callback function
RegisterEvent(EVENT_1,test_callback_1);
RegisterEvent(EVENT_2,test_callback_2);
}
Posted by 三更天 at December 5, 2005 08:27 PM
|