Reputation: 99
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!
Upvotes: 1
Views: 769
Reputation: 24146
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);
Upvotes: 1
Reputation: 726479
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.
Upvotes: 3