user2793162
user2793162

Reputation:

Using function pointer as callback

In some SDK I have a method which takes function pointer.

int AutoRead(nAutoRead aEventFun)

where parameter is:

typedef int (__stdcall *nAutoRead)(char *data);

Now I want to use this function in my code like this:

    // First need to get pointer to actual function from DLL
    CV_AutoRead AutoRead; // CV_AutoRead is typedef for using function pointer 

    AutoRead = (CV_AutoRead)GetProcAddress(g_hdll,"AutoRead");

   // Now I want to use the SDK method and set callback function, 
   // but I get error on the next line
   // error is: 'initializing' : cannot convert from 'int (__cdecl *)(char *)' to 'TOnAutoRead'
   nAutoRead f = &callbackFunc;
   if(0 == AutoRead(f))  // AutoRead - now refers to the SDK function shown initially
   {

   }

where callbackFunc is:

int callbackFunc(char *data)
{

}

Apparently I am doing something wrong. But what?

ps. This is typedef for CV_AutoRead

typedef int (CALLBACK* CV_AutoRead)(nAutoRead aEventFun);

Upvotes: 2

Views: 123

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

This has to do with the calling convention specifier __stdcall that the callback requires. By default your callbackFunc uses __cdecl, causing an error.

To fix this problem, declare callbackFunc as follows:

int __stdcall callbackFunc(char *);

You also need to add __stdcall to the function definition.

See Argument Passing and Naming Conventions for more information on this subject.

Upvotes: 1

Related Questions