Using TCallBack

This document describes the TCallBack class.

The class encapsulates a pointer to a function which takes an argument of type TAny* and returns a TInt. The class is generally useful but, in particular, simplifies the programming interface of the CIdle and CPeriodic classes.

Given a suitable function and a pointer to an object, a callback is constructed simply. The function must be a non-member function or a static member of a class. For example:

TInt Foo(TAny *);  // a non-member function
X* pX=new X;       // a class X object

or, as a static member of class X:

TInt X::Foo(TAny *); // a static function of class X
X* pX=new X;         // a class X object

A callback function returns a true value to indicate whether it should be called again. This is important when used with the CIdle and CPeriodic classes. The following code fragment shows the programming paradigm:

TCallBack cb(Foo,pX);  // construction of the callback
for (;;)
 if (!cb.CallBack()) // invoke callback until it returns
  {    // a false value

Calling cb.CallBack() results in a call to the callback function Foo() passing it the pointer pX.

A common requirement is for the callback function to be a non-static member of a class. This can be implemented by passing, to the callback function, a pointer to an instance of the class of which it is a static member. For example:

class X
 static X* NewL();
 static TInt Foo(TAny* pX);
 TInt DoFoo();

where the static function Foo() is implemented as:

static TInt X::Foo(TAny* pX)
 return ((X*)pX)->DoFoo();

Typically, create an instance of class X and, at some later stage, create the callback:

X* pX = X::NewL();
TCallBack cb(Foo,pX);