user1767754
user1767754

Reputation: 25094

Definition of Function Pointers

i am working with an sdk, where i have to define a call-back function, the problem is, that the "sample" code are shipped with global functions and a very procedural approach. To bring it into a structure, i was creating classes. But i couldn't get the argument syntax right, when defining and declaring it O_o

So here is my working example:

In my code.h:

void   (*MessageHandler)(int msgType, char* msg){printf("\n%s\n", msg);}

this works fine, when i call in my code.cpp

void (*opFunc)(int msgType, char* msg) =  MessageHandler;

But i want to do the definition in my cpp, and i couldn't find the syntax, normally it should be:

void (*Code::MessageHandler)(int msgType, char* msg){
    printf("\n%s\n", msg);
}

But this doesn't work and i couldn't find any hint how to fix it. Would be nice to get a hint!

Upvotes: 1

Views: 100

Answers (2)

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33046

Since it is a function, define it as you would do with any function:

void Code::MessageHandler(int msgType, char* msg){
    printf("\n%s\n", msg);
}

Its name, Code::MessageHandler is actually a function pointer of the right type. This works as expected if Code is a namespace, if it is a class, you'll have to declare it static to get an unbound reference.

Also, consider using typedef to make the source code more readable.

Upvotes: 1

RandyGaul
RandyGaul

Reputation: 1915

It looks like you're trying to define a function for a function pointer within your Code class? You can just create a function (either static member or global function) and use the name of that function as a pointer.

void Code::MessageHandler( int msgType, char* msg ){
  printf( "\n%s\n", msg );
}

// Create a function pointer called fn to point at a static function
void (*fn)( int, char * ) = &Code::MessageHandler;

Note again, that this won't work if MessageHandler is not a static function, otherwise you'd be dealing with member function pointers, which are very different from function pointers.

If you wanted Code::MessageHandler to itself be a function pointer, then you'd assign it to a global function upon construction.

Upvotes: 1

Related Questions