Re: gdk_input_add() with class member as callback problem



Eelco Schijf a écrit :
Hi,

I'm stuck with the gdk_input_add() function and could use a hint to solve the problem. So here goes;

The callback function I want to call is a member of a class, but g++ won't compile this. Placing the function outside the class works, but this is not the solution I'm looking for.

The code:

InputLirc :: InputLirc()
{
 ...

 tag = gdk_input_add( sock,
     GDK_INPUT_READ,
     &InputLirc::ProcessLircInput,
     NULL );

 ...
}

void InputLirc :: ProcessLircInput( gpointer data, gint source, GdkInputCondition condition )
{
 ...
}

In C++, pointer to (class) methods are not equal to pointer to functions.

Class methods has an invisible additional argument which is the pointer to the instance. Thus, the "signature" of a method is not the same as the "signature" of a function (i.e: void (InputLirc::*)(...) is not equal to void(*)(...)). So, when calling a method of an object, the compiler needs two informations: the object and the method.

gdk_input_add expects a pointer to a function and a user data.
So you must create a dispatch function that calls the object method. It looks from your code that you don't need the user data, so you can use it to pass the instance of your object. The dispatch function can also be a static method of your class, as static methods are handled as normal functions (they do not apply to instances of the class, so they do not use the invisible argument described previously). So one solution would be:

class InputLirc
{
public:
static void DispatchProcessLircInput (gpointer aInputLirc, gint source, GdkInputCondition condition)
 {
        InputLirc *obj = static_cast<InputLirc*>(aInputLirc);
        return obj->ProcessLircInput (NULL, source, condition);
}

InputLirc :: InputLirc()
{
 ...

 tag = gdk_input_add( sock,
     GDK_INPUT_READ,
     DispatchProcessLircInput,
     this );

 ...
}


See http://www.newty.de/fpt/functor.html for more information.



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]