Reputation: 21996
I have a problem handling a function pointer.I have made a class Control that has a function pointer as member:
void (*mouseFunction) (Control*, Event*);
The member is protected, and it has setter and getter:
void (*getMouseFunction()) (Control*,Event*)
{
return mouseFunction;
}
void setMouseFunction( void (*mouseFunction) (Control*, Event*) )
{
this->mouseFunction=mouseFunction;
}
The problem is that even after setting the pointer, it's always NULL.
I have a function declared inside a header file:
void mouseFunction (Control* control, Event* event)
{
std::cout << "Inside Text Field";
}
If I try to assign it:
myControlInstance.setMouseFunction(mouseFunction);
If I use the getter to get the pointer it's NULL; and if I try to execute the function I get EXC_BAD_ACCESS:
error: address doesn't contain a section that points to a section in a object file
Upvotes: 2
Views: 848
Reputation: 704
Your problem might be with inlining. Since the function is declared and defined at the same point, and inside a header.. the compiler may be treating it as an implicit inline (please note that it is up to the compiler to decide whether or not to actually inline it). If the function is inlined, then the compiler would have to jump through some extra hoops to make it possible to store a pointer to that function (i.e., the compiler would have to have a non-inline version of the function built). If the compiler doesn't make this happen, then you're going to have problems storing and calling a function pointer to the function.
To eliminate this as a possible source of the problem, try moving the function's implementation out into a cpp file, which is one common way to prevent implicit inlining (and usually better style anyway).
Upvotes: 0
Reputation: 658
Following cod is working, so be sure that youre method is public to be accessible from other place than object.
typedef int Event;
class Control
{
public:
void (*mouseFunction) (Control*, Event*);
void (*getMouseFunction()) (Control*,Event*)
{
return mouseFunction;
}
void setMouseFunction( void (*mouseFunction) (Control*, Event*) )
{
this->mouseFunction=mouseFunction;
}
};
void mouseFunction (Control* control, Event* event)
{
printf ("test");
}
int _tmain(int argc, _TCHAR* argv[])
{
Control c;
c.setMouseFunction(mouseFunction);
Event e = 1;
c.mouseFunction(&c,&e);
return 0;
}
Upvotes: 1