从外部std::函数获取函数指针的干净方式



因为C,我需要一个函数指针fromstd::function在运行时接收。
让我们调用defineProxyCallback这个C函数,它接受unsigned char的函数作为输入。我的方法是:

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);
}

这可以工作,但它很难看。然而,因为函数指针来自静态函数,我没有找到任何其他方法,而不是使用extern。

我四处寻找,但我从来没有找到一个解决这个问题的方法。有什么让它更干净的建议吗?

非常感谢!

为清楚起见:I不能更改我需要提供一个指向defineCallback的函数指针,而不是从外部接收std::函数。

我不认为这将是超级整洁。如果是我,我可能会使用inline函数,这样它们就可以放在头文件中,我会使用thread_local存储来增加一点线程安全。

有点像这样:

// 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);
}

最新更新