我如何传递一个C ++ lambda来一个C-回调需要一个函数指针和一个环境? [英] How can I pass a C++ lambda to a C-callback that expects a function pointer and a context?
问题描述
我想注册在使用标准的函数指针+环境范例的C-API的回调。这里的API是什么样子:
I'm trying to register a callback in a C-API that uses the standard function-pointer+context paradigm. Here's what the api looks like:
void register_callback(void(*callback)(void *), void * context);
我真正想要做的是能够注册一个C ++的lambda作为回调。此外,我想拉姆达是一个已经抓获变量(即不能转换为直线无国籍的std ::功能
)
我需要什么样的适配器code的写入可以注册一个lambda作为回调?
What kind of adapter code would I need to write to be able to register a lambda as the callback?
推荐答案
简单aporoach是将拉姆达粘成一个的std ::功能<无效()>
这是什么地方保留。可能是在堆上分配的,只是由无效*
与服用回调实体注册引用。然后回调,简直是一个功能线这样的:
The simple aporoach is to stick the lambda into a std::function<void()>
which is kept somewhere. Potentially it is allocated on the heap and merely referenced by the void*
registered with the entity taking the callback. The callback would then simply be a function line this:
extern "C" void invoke_function(void* ptr) {
(*static_cast<std::function<void()>*>(ptr))();
}
注意的std ::功能&LT; S&GT;
可容纳状态函数对象,例如,一个非空捕捉波长的职能。你可以注册一个回调是这样的:
Note that std::function<S>
can hold function objects with state, e.g., lambda functions with a non-empty capture. You could register a callback like this:
register_callback(&invoke_function,
new std::function<void()>([=](){ ... }));
这篇关于我如何传递一个C ++ lambda来一个C-回调需要一个函数指针和一个环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!