c – 如何使用std ::函数作为C风格的回调

如何在需要C风格回调的函数中使用std ::函数

如果不可能,下一件最好的事情是什么?

例:

// --- some C code I can not change ---
typedef void(*fun)(int);
void register_callback(fun f) {
    f(42); // a test
}
// ------------------------------------

#include <functional>
#include <iostream>

void foo(const char* ptr,int v,float x) {
    std::cout << ptr << " " << v << " " << x << std::endl;
}

int main() {
    std::function<void(int)> myf = std::bind(&foo,"test",std::placeholders::_1,3.f);
    register_callback(myf); // <-- How to do this?
}

解决方法

长答案:您可以编写一个C函数传递给调用您的std ::函数的API:
// --- some C code I can not change ---
typedef void(*fun)(int);
void register_callback(fun f) {
    f(42); // a test
}
// ------------------------------------

#include <functional>
#include <iostream>

void foo(const char* ptr,float x) {
    std::cout << ptr << " " << v << " " << x << std::endl;
}

namespace {
std::function<void(int)> callback;
extern "C" void wrapper(int i) {
    callback(i);
}
}

int main() {
    callback = std::bind(&foo,3.f);
    register_callback(wrapper); // <-- How to do this?
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...