且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何传递一个C ++ lambda来一个C-回调需要一个函数指针和一个环境?

更新时间:2023-02-14 17:53:45

简单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()>([=](){ ... }));