Re: Reference to a C++ object in GTK+ callbacks



On Wed, 2005-12-14 at 12:49 -0700, Daryl Lee wrote:
Well, thanks for the correction.  I will have to go back through my
projects to understand why I thought that.

On Wed, 2005-12-14 at 11:19 -0800, Stephen Pollei wrote:
On 12/13/05, Daryl Lee <dlee altaregos com> wrote:
...
C++ functions do, indeed, have to be "static" to be used as GTK+
callbacks.
Untrue I just removed the static keyword from 8 of my callbacks and
then recompiled, worked just fine. 
...

Warning!

It may work for you.  It's not portable.  C++ implementations are free
to use a calling convention different from the C calling convention: In
C, parameters are pushed in reverse order to support varargs.  C++
functions are specified in the standard as not supporting varargs so
that compiler vendors are free to use certain optimizations.  For
example, in C, it's the caller's responsibility to clean up the stack
after a call because the called function can't know at compile time how
many parms were passed.  C++ compilers are free to optimize this such
that the called function does the stack cleanup, so that a function
that's called from many different places only has one stack cleanup
chunk generated.

It's for this reason that a static function should be used to catch
callbacks, so it can cast the parameter to a pointer to the object, then
invoke the member function.  Static member functions don't have an
implied first parm that's it's object.  See below:

class Foo
{
public:
        static redrawCB(Event *event, void *parm)
        {
                Foo *obj = reinterpret_cast<Foo*>(parm);
                obj->redraw(event);
        }
        
        redraw(Event *event)
        {
          ...
        }
};

Gtkmm doesn't need to go through a static member because in Gtkmm you
derive from it's classes and it invokes through the vtable.


  // Wally




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