如何std::function
在需要C风格回调的函数中使用?
如果这是不可能的,那么下一个最好的事情是什么?
例:
// --- some C code I can not change --- typedef void(*fun)(int); void register_callback(fun f) { f(42); // a test } // ------------------------------------ #include#include void foo(const char* ptr, int v, float x) { std::cout << ptr << " " << v << " " << x << std::endl; } int main() { std::function myf = std::bind(&foo, "test", std::placeholders::_1, 3.f); register_callback(myf); // <-- How to do this? }
Drax.. 13
在大多数情况下,你不能.
但是如果你在std :: function中存储了一个C风格的回调函数,你可以使用target()成员函数.
答案很长:有点儿.您可以编写一个C函数来传递给调用您的API std::function
:
// --- 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; } namespace { std::function<void(int)> callback; extern "C" void wrapper(int i) { callback(i); } } int main() { callback = std::bind(&foo, "test", std::placeholders::_1, 3.f); register_callback(wrapper); // <-- How to do this? }
在大多数情况下,你不能.
但是如果你在std :: function中存储了一个C风格的回调函数,你可以使用target()成员函数.