Tuesday, July 7, 2009

How to uses callback function for C++

 
// This is a callback function sample without parameter.
void callbackProc1()
{
    printf("this is a call back 1..\r\n");
}
 
// This is a callback function sample with 2 parameters
bool callbackProc2(int nSize, char* pszName) {
    printf("this is a call back 2..\r\nSize is:%d  pszName is:%s \r\n", nSize, pszName);
    return true;
}
 
// This function invoke callback function as a parameter to it
void test1(void(*p)(void))
{
    p();
}
// This function invoke a callback function with 2 parameters
void test2(bool(*p)(int, char*), int param1, char* param2)
{
    if(p(param1, param2))
    {
        printf("the callback func return TRUE.......\r\n");
    }
}

void main()
{
    // this is a sample to demonstrate how to invoke a callback function without parameter
    // the callback function name is a memory address reference to callback function.
    test1(callbackProc1);
   
    // this is a sample shows how to invoke a callback functions with two parameters
    test2(callbackProc2, 999, "johnrock");