// demofp3.cpp - demonstrate function pointer communication #include using namespace std; ////////////////////////////////////////////////////////// // module using function pointers defines the callback // // signature and the function(s) using callbacks // ////////////////////////////////////////////////////////// // declare a funPtr type taking a void* argument typedef void(*funPtr)(void* dptr); void fun1(funPtr fptr, void* dptr) { // this is function using // callback argument cout << " fun1 calling "; fptr(dptr); // invoke the function pointed to } // note that this module doesn't // know what fptr does nor its // input data structure /////////////////////////////////////////////////////////////// // client code defines the callback functions and contents // // of their calling parameter(s) // /////////////////////////////////////////////////////////////// // client supplied callback input data struct myStruct { int x; // it can hold anything the design needs double y; }; // client supplied callback function void fun2(myStruct* ms) { cout << "fun2(myStruct* ms)\n" << " ms->x = " << ms->x << "\n" << " ms->y = " << ms->y << "\n"; } int main() { cout << "\n\ndemonstrating callback communication\n\n"; myStruct ms = { 1, 2.5 }; funPtr callback; // declare a function pointer callback = (funPtr)fun2; fun1(callback, (void*)&ms); // pass the function pointer, argument // cast is necessary cout << "\n\n"; return 0; }