2

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);

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

8 Comments

seems to compile now. Thanks. added _stdcall to both function declaration and definition. ps. Am I using the function pointer correctly ? e.g., TOnAutoRead f = &callbackFunc; if(0 == AutoRead(f)) ??
__stdcall should go also in the function definition?
@dmcr_code I think you're right, the doc says that to use __stdcall you need to have a prototype, but it looks like __stdcall needs to be on the definition as well.
and finally, just tell me if I use it correctly, e.g., TOnAutoRead f = &callbackFunc; if(0 == AutoRead(f))?? Is this usage correct? The way I pass func pointer as parameter?
@dmcr_code That's one way. You can also pass it without making a variable or taking an address, and use ! to zero-check the return the C style, i.e. if (!AutoRead(callbackFunc)) ...
|

Your Answer

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