ke************* ***@yahoo.co.uk wrote:
Hi thanks for the reply,
I have decided to implement this using int pointers to the function
instead of void pointers.
int CliComponent::r unAction()
{
// do something
}
Do I still need to use the function callback.
Can I do this:
bool Scheduler::setS chedule( int interval, ComponentInterf ace&
CliComponent)
{
p_ClientCompone nt = &CliComponen t;
scheduler.AddTa sk(interval, p_ClientCompone nt->runAction, 0);
return true;
}
int Scheduler::Add( const unsigned long timeout, int* pFunction, void*
pParam)
This of course does not work.
Thanks again
The question is how to specify a member function pointer as a callback
routine. The problem with passing a member function pointer such
&ComponentInter face::runAction is that the function accepting the
callback needs to expect a member function pointer for that particular
class, in this case, ComponentInterf ace:
int Scheduler::Add( const unsigned long timeout,
int (ComponentInter face::*)())
Since the Add() method has to know the member function's class, then
there is little reason for it not to know which member function in that
class it should be calling. So why bother with the callback at all? Why
not just pass a ComponentInterf ace pointer? In other words, because a
member function pointer is class-specific, it is not suitable for use
as a generic callback routine.
There is a solution however. Most callbacks consist of a function
pointer and a "user data" pointer that is passed to the function when
it is called. This data pointer allows the callback routine to
"recover" an object and then call its appropriate method. Such an
approach would look something like this:
The function accepting the callback also accepts a user data pointer:
int Scheduler::Add( const unsigned long timeout,
int (*inCallback)(v oid *),
void *inUserData)
The client specifies the callback like so:
{
ComponentInterf ace theComp;
scheduler->Add(0, MyCallBack, &theComp);
and the callback routine itself:
int MyCallBack( void *inMyData)
{
ComponentInterf ace * component;
component = static_cast<Com ponentInterface *>(inMyData);
component->runAction();
}
This technique is not ideal since type information is lost and then
recovered. But it does help to prevent unnecessary dependencies
between the callback and the caller.
Greg