[ Return to Articles | Show Comments | Submit Comment ]
Article #379: How Can I Use a Class Method as a Callback?
Created at 10:59 Jan 29, 2005 by mike
Because of the way C++ and FLTK work, you can only use static methods for
callbacks, at least directly.
To get the this pointer for the class you can pass the
pointer as the user_data argument for your callback. Typically
this is then used to call a non-static method:
class MyClass {
static static_callback(Fl_Widget* w, void* data) {
((MyClass*)data)->real_callback(w);
}
void real_callback(Fl_Widget* w) {
... this is the real callback ...
}
public:
MyClass() {
...
// building the gui now:
button = new Fl_Button(...);
button->callback(static_callback, this);
}
};
If you need the user_data pointer for something else, you can
also set the user_data pointer in the top-most group/window in
your class, and then use the Fl_Widget pointer that is passed to
your callback to find the class pointer (this is the method used by FLUID):
class MyClass {
static static_callback(Fl_Widget *w, void *data) {
Fl_Widget *p = w->parent();
while (p->parent()) p = p->parent();
((MyClass*)p->user_data())->real_callback(w, data);
}
void real_callback(Fl_Widget *w, void *data) {
... this is the real callback ...
}
public:
MyClass() {
...
// building the gui now:
window = new Fl_Window(...);
window->user_data(this);
button = new Fl_Button(...);
button->callback(static_callback, ...);
}
};
[ Download | Home Page | Listing ]
[ Submit Comment ]From NULL, 06:42 Nov 13, 2005 (score=3)
static static_callback(Fl_Widget *w, void *data) {
Fl_Widget *p = w->parent();
while (p->parent()) p = p->parent();
((MyClass*)p->user_data())->real_callback(w, data);
}
There is a bug in this method, if you use this on Fl_Window you will have seg fault.
Fl_Widget *p = w; // should be used insted of
Fl_Widget *p = w->parent();
[ Reply ] |