does C\C++ Support a mechanism for callback function ? and how to create it ? I've written several code, to create callback function in C++ but it failed ..
#include<iostream>
using namespace std;
void callee()
{
printf("callee\n");
printf("calleeeeeeeeee\n");
}
void callback(void* func)
{
printf("callback\n");
}
int main()
{
void (*call)(void*);
void (*call2)(void);
call2 = &callee;
call = &callback;
call((void*)call2);
getchar();
return 0;
}
I don't know C++, I wrote up some C code, hope it helps
#include <stdio.h>
void call( int, void ( *f )( int ) );
void called( int );
int main( int argc, char const *argv[] ){
printf( "start\n" );
call( 1, called );
printf( "end\n" );
getchar();
return 0;
}
void call( int a, void ( *f )( int ) ){
printf( "doing stuff\n" );
printf( "a: %d\n", a );
printf( "going to call back\n" );
f( a * 2 );
}
void called( int b ){
printf( "b: %d\n", b );
printf( "b*2: %d\n", b*2 );
printf( "call back function being called\n" );
}
Calling call back functions in a function is no more than having a function pointer and call the function whenever you finished your planed job.
I modified the code and made it up to be more clear to show how you would use call backs.
This is the result you will see, if you compile and run it:
start
doing stuff
a: 1
going to call back
b: 2
b*2: 4
call back function being called
end
Well, either the author edited the question or someone edited it for him, there's no longer the C tag. Ignore this answer if you don't want to see pure C code. I'm just gonna leave it here in case anyone could be interested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With