>> I'm having problems understanding/using function pointers. I'm trying to use a member function of an instantiated class i.e. non-static as a call back function and need to pass a function pointer to the caller.
You can't. The member function requires a pointer to *this, so logically it's type is closer to:
int ( * )( MyClass*, int, int )
>> Unfortunately I cannot change the calling function as it is code not written by myself and it is has been written in C.
The only way to do it then would be a function that uses a global variable, eg:
Code:
int add_callback( int a, int b )
{
// myClassObject is defined elsewhere in the program
return myClassObject.add( a, b );
}
Another option, and this is a bit of a hack:
Code:
int add_callback_hack( int a, int b )
{
static MyClass* ptr = 0;
if( a == numeric_limits< int >::max( ) )
ptr = ( MyClass* )b;
return ptr->add( a, b );
}
int main(){
MyClass mc;
add_callback_hack(numeric_limits<int>::max(), int(&mc));
int (*fp)(int,int) = add_callback_hack;
}
EDIT: I honestly wouldn't recommend the hack, though, as it's error-prone and could potentially lead to some nasty bugs!
EDIT#2: Ok, so I've come up with a much better hack, and it's totally safe.
Code:
int add_callback_hack( int a, int b, MyClass* instance )
{
static MyClass*
ptr = 0;
if( instance )
ptr = instance;
return ptr->add( a, b );
}
inline void add_callback_init( MyClass* instance )
{
add_callback_hack( 0, 0, instance );
}
int add_callback( int a, int b )
{
return add_callback_hack( a, b, 0 );
}
int main(){
MyClass mc;
add_callback_init(&mc);
int (*fp)(int,int) = add_callback;
}