如何在需要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? }