如何在需要 C 风格回调的函数中使用 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;
}
int main() {
std::function<void(int)> myf = std::bind(&foo, "test", std::placeholders::_1, 3.f);
register_callback(myf); // <-- How to do this?
}
最佳答案
在大多数情况下你不能。
但是当您在 std::function
中存储 C 风格的回调时,您可以使用 target()
成员函数。
关于c++ - 如何使用 std::function 作为 C 风格的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20290476/