Search code examples
c++callbackvisual-studio-2015fltk

VS 2015 and FLTK Callback issue


I am trying to move my FLTK projects and compile it under the VS 2015 community edition. While do this, I am getting error. I have a code like below:

#include <Fl/....>
....
class CWindow
{
private:
    ....
    Fl_Input *_textInputEditor;
    ....
    void _cbTextInput(Fl_Widget *refObject, void *objData)
    {
        // Do something when callback is triggered.
    }
public:
....
    void createWindow()
    {
        ....
        _textInputEditor = new Fl_Input(....);
        _textInputEditor->when(FL_WHEN_ENTER_KEY);
        _textInputEditor->callback((Fl_Callback*)&CWindow::_cbTextInput, this);
        ....

When I try to compile, I get an error:

Error C2440 'type cast': cannot convert from 'void (__thiscall CWindow::* )(Fl_Widget *,void *)' to 'Fl_Callback (__cdecl *)

This same code compiles with MinGW 5.x perfectly (IDE: C::B) under Win 7.

Can someone help me here? I want a call back to a private method of my CWindow class.


Solution

  • The signature is incorrect. _cbTextInput should be static. The problem then will be access to member variables.

    static void _cbTextInput(Fl_Widget *refObject, void *objData)
    {
        // No access to member variables so cast it to a CWindow* to get
        // at the member variables
        CWindow* self = (CWindow*) objData;
        self->cbTextInput();
    
        // Alternatively, if you do not wish to write another routine,
        // you will need to put self-> in front of every member variable
        // you wish to access.  Just personal preference: some people prefer
        // it that way.
    }
    
    void cbTextInput()
    {
        // This has access to member variables
        ...
    }