> The callback function is where I'm stuck. Its entire purpose is
> to read the incoming value and store it to an array. Since my
> callback has to be static (right!?, is there a way to make a
> non-static callback function? another topic...) I pass a pointer
> to my UI object which contains the array that I want to update.

That's not quite true. The callback has to be "visible", for want
of a better word. Therefore you can use either a member function
declared as static, i.e. a class function, or you can use a plain
old function. In most cases you need to pass in a pointer to the
object via the void* user_data parameter, which you cast back to
a YourClass* pointer.

The advantage of a static member function is that it is part of
the scope of the class, so it can access private member functions.

A plain old function is not quite so confusing for new users, but
can only access public member variables and functions, which opens
a loophole in the data encapsulation.

So, provided there are no typos, you can have something like:

void plainOldFunction(Widget* widget, void* userData)
{
    YourClass* yc = (YourClass*)userData;
    yc->publicMemberFunction(widget, userData);
}

or

static
void YourClass::staticClassMethod(Widget* widget, void* userData)
{
    YourClass* yc = (YourClass*)userData;
    yc->otherMemberFunction(widget, userData);
}

Obviously publicMemberFunction must be declared as "public" but
otherMemberFunction can be public, protected or private.

I find it easier to maintain the widget and userData parameters
in the member functions that provide the real implementation of
the callback. This allows you to access the widget directly to
get/set its state even if you use the same callback for multiple
widgets, or the widget is not available via a member variable.

I don't cast it to the specific widget type until I need it, as
it is less confusing if all functions in the callback chain have
the same signature, and also avoids retyping if I decide to use
a different widget. It's a pretty marginal saving: you might want
to cast from Widget* to SpecificWidget* in the initial callback,
and adjust the parameter types of the real callback implementation.

I have to admit that this up- and down-casting of pointers in
order to achieve specific polymorphic behaviour is something that
took me a long time to get straight in my own head.

So I hope this explanation has helped, rather than confused.

Cheers
D.

_______________________________________________
fltk mailing list
[email protected]
http://lists.easysw.com/mailman/listinfo/fltk

Reply via email to