【问题标题】:How to make a callback global so I can use it to other functions?如何使回调全局化,以便我可以将其用于其他功能?
【发布时间】:2015-10-09 20:37:44
【问题描述】:

我声明了一个这样的函数:

int __stdcall DoSomething(int &inputSize, int &outputSize, void(* __stdcall progress)(int) )
{
}

如何使 progress() 回调一个全局变量以在同一个 DLL 中的其他函数中使用它? 我是 C++ 的新手。

【问题讨论】:

  • 只使用progress作为参数?
  • @deviantfan 但是这个另一个函数应该以同样的方式声明进度参数吗? void(* __stdcall 进度)(int) ?
  • @Tom 是的,应该。
  • 还可以考虑使用typedef 作为函数指针类型。这使事情看起来更好,尤其是当各种函数将其作为参数时。 (如果您需要修改回调的签名,这会让事情变得更容易。)
  • @TheUndeadFish Typedef 很棒,谢谢!

标签: c++ dll stdcall


【解决方案1】:

创建一个具有匹配签名的函数(即void (*)(int))。

#include <iostream>

//void (      *      )(     int    ) - same signature as the function callback
  void progressHandler(int progress)
{
    std::cout << "received progress: " << progress << std::endl;
}

int DoSomething(int &inputSize, int &outputSize, void (*progress)(int))
{
    progress(100);
    return 0;
}

int main()
{
    int inputSize = 3;
    int outputSize = 3;
    DoSomething(inputSize, outputSize, progressHandler);

    return 0;
}

输出:

received progress: 100

即使我删除了它(因为我使用了g++),你也可以保留__stdcall

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-01
    • 2019-01-11
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    相关资源
    最近更新 更多