gpt4 book ai didi

c++ - 从外部 std::function 获取函数指针的干净方法

转载 作者:行者123 更新时间:2023-12-05 01:04:16 28 4
gpt4 key购买 nike

因为 C,我需要一个 函数指针,来 self 在运行时收到的 std::function
让我们调用 defineProxyCallback 将一个 unsigned char 函数作为输入的 C 函数。我完成这项工作的秘诀是:

struct callBacker {
std::function<void(unsigned char)> normalKey;
};
callBacker cb = callBacker();
extern callBacker cb;
void proxy(unsigned char c) { cb.normalKey(c); };

void maincode {
// Actually cb.normalKey is taken as an input from outside
cb.normalKey = [](unsigned char c){std::cout << c << std::endl;} ;
// this was just to lake the code work
defineCallback(proxy);
}

defineCallback 在其他地方定义:

void defineCallback(void (*func)(unsigned char))
{
*func("hello world");
//should be : glutKeyboardFunc(func);
}

这可行,但它是丑陋的 AF。但是因为函数指针来自于静态函数,所以除了使用extern,我没有找到其他方法。

我环顾四周,但从未找到解决这个确切问题的方法。有什么让它更干净的提示吗?

非常感谢!

为了清楚起见:我不能改变我需要提供一个函数指针来defineCallback,也不能从外部接收一个std::function。

最佳答案

我认为这永远不会 super 整洁。如果是我,我可能会使用 inline 函数,以便它们可以放入 头文件,我会使用 thread_localstorage 添加一点线程安全。

有点像这样:

// force the compiler to make sure only one of these functions
// is linked and this can go in the header file
inline std::function<void(unsigned char)>& get_std_function()
{
// returns a different object for each thread that calls it
static thread_local std::function<void(unsigned char)> fn;
return fn;
}

inline void proxy(unsigned char c){ get_std_function()(c); };

void maincode() {
// Actually cb.normalKey is taken as an input from outside
get_std_function() = [](unsigned char c){std::cout << c << std::endl;} ;

// this was just to lake the code work
defineCallback(proxy);
}

关于c++ - 从外部 std::function 获取函数指针的干净方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72430636/

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