1

I would like to forward a callback to a function pointer. So I declare a static (int*) m_pointer1, as well as a method void RegisterCallback1( (int*)fct)

in class1.h:

public:
   int RegisterCallback1( int (*fct) );
private:
   static int (*m_Callback1);

in class1.cpp:

int class1::RegisterCallback1( int (*fct) )
{
    m_Callback1= fct;
}

then, I want to forward the callback to the function pointer:

void class1::Callback1()
{
   (*m_Callback1)();
}

But I get a compiler error "Expression must have (pointer-to)- function type I have followed tutorial and read about function pointers and they seem to do it this way without any problems. Any ideas why?

EDIT: So, I declare (int*)(void)m_Callback1 -Visual Studio requires a void there...- Then how do I call the registerCallback function with the argument?

class1.RegisterCallBack1(  ??? - class2::callback -??? );

3 Answers 3

7

static int (*m_Callback1) does not declate a function pointer, just a pointer to int: you forgot about the parameter list. You meant:

static int (*m_Callback1)();

and

int RegisterCallback1( int (*fct)() );
Sign up to request clarification or add additional context in comments.

1 Comment

Thats great, but then how to I pass it to RegisterCallback1? I tried something like class1.RegisterCallback1( (int*) class2::callback ); and many combinations, they all seems to give me an error? Always something with argument of type int* incompatible with (int*)()
6

You haven't declared a function pointer, you've declared a normal data pointer. You are missing () at the end of the declaration.

3 Comments

Thats great and all, but then how do I call the registerCallback1 function with an argument? class1.RegisterCallBack1( ??? - class2::callback -??? );
@David : Assuming class2::callback is static, c1.RegisterCallBack1(&class2::callback).
this gives out another error: argumen of type void(__stdcall )() is not compatible with parameter of type void()(). If I add __stdcall to function pointer decleration, I get linking errors, saying that m_callback1() cannot be found in class1 (not class2)
1

You can try to limit the missing () errors pointed out by Oli and Dave by using a typedef for the callback function's signature: typedef int (*)() CallBack; This would at least have the merit of letting you think once about the precise number of brackets rather than at every point in your code where you use such a function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.