문제

I was writing an interface(using FLTK but this doesn't matter). I made a button and its callback function. In this callback function I need to use data in a variable outside the callback function(which is Myclass mc in the code). The code looks like the following (I didn't paste the unnecessary parts):

class Myclass
{
    ...
}

void button_callback( Fl_Widget* o, void* data) 
{
   Fl_Button* button=(Fl_Button*)o;
   Myclass *a;
   a=data;
   a->MyMemberFunction();
}

int main()
{
    Myclass mc;
    ...
    Fl_Button button( 10, 150, 70, 30, "A button" );
    button.callback( button_callback,&mc );
    ...
}

However at the place of "a=data;" I got an error saying void * cannot be assigned to Myclass *, what should I do?

Many thanks!

도움이 되었습니까?

해결책

Assuming that the data coming in through the void* is a pointer to Myclass, you need to add a reinterpret_cast from the void*, like this:

Myclass *a = reinterpret_cast<Myclass*>(data);

This will tell the compiler that you know for sure that the data is a pointer to Myclass, letting you call MyMemberFunction() through that pointer.

다른 팁

you need to use any kind of type casting:

here is C variant:

Myclass *a = (Myclass*)data;

here is C++ variant:

Myclass* a = reinterpret_cast<Myclass*>(data);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top