正在DLL中注册回调函数

Registering callback function in DLL

本文关键字:回调 函数 注册 DLL 正在      更新时间:2023-10-16

我有一个简单的测试函数,我希望DLL中的代码回调

 void user_function_stats( int )
{
    cout << "Stats!n";
}

因此,在头文件中,我指定了一个typedef

typedef void (CALLBACK *stats_user_function)( int );

以及注册回调的DLL函数

void DLL_EXPORT getbar_client_set( stats_user_function pf );

这应该让我在用户代码中注册回调函数为

getbar_client_set(  & user_function_stats );

但是编译器抱怨

main.cpp|14|error: invalid conversion from 'void (*)(int)' 
   to 'stats_user_function 
   {aka void (__attribute__((__stdcall__)) *)(int)}' [-fpermissive]|

我已经尝试将CALLBACK添加到用户功能的定义中

void CALLBACK user_function_stats( int )
{
 cout << "Stats!n";
}

但是现在我得到了这个编译错误

undefined reference to `_imp__getbar_client_set'|

该令牌CALLBACK实际上是Windows的调用约定说明符。它不必用于进行回调。Windows内部只是对回调使用不同的调用约定,而不是标准的C/C++调用约定。你可以做两件事中的任何一件。

您可以从typedef中删除CALLBACK令牌,即

typedef void (*stats_user_function)( int );`

或者用CALLBACK标记声明回调函数,该标记扩展为__stdcall__调用约定说明符,即

void CALLBACK user_function_stats( int )
{
    cout << "Stats!n";
}