gpt4 book ai didi

c++ - 如何使用 std::function 作为 C 风格的回调

转载 作者:IT老高 更新时间:2023-10-28 22:35:18 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com