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::runAction()
{
// do something
}
Do I still need to use the function callback.
Can I do this:
bool Scheduler::setSchedule( int interval, ComponentInterface&
CliComponent)
{
p_ClientComponent = &CliComponent;
scheduler.AddTask(interval, p_ClientComponent->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
&ComponentInterface::runAction is that the function accepting the
callback needs to expect a member function pointer for that particular
class, in this case, ComponentInterface:
int Scheduler::Add( const unsigned long timeout,
int (ComponentInterface::*)())
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 ComponentInterface 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)(void *),
void *inUserData)
The client specifies the callback like so:
{
ComponentInterface theComp;
scheduler->Add(0, MyCallBack, &theComp);
and the callback routine itself:
int MyCallBack( void *inMyData)
{
ComponentInterface * component;
component = static_cast<ComponentInterface*>(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