简体   繁体   English

通过lambda从C ++调用C回调函数

[英]Calling a C callback function from C++ via a lambda

I have this code in a plain C static library: 我在一个普通的C静态库中有这个代码:

extern "C" {
    typedef void (__cdecl* VisitChildren)(Option*);
    void __cdecl DoVisitChildren(Children* List, VisitChildren Visitor);
}

And I'm trying to use it from some C++ code (unit tests) using a lambda. 我正在尝试使用lambda从一些C ++代码(单元测试)中使用它。

...
DoVisitChildren(children, [&] (Option* option) {
...
});

I'm getting the compiler error C2664 ... cannot convert parameter 2 from 'unittests::UnitTest1::TestBuild::<lambda_b286d160b9bab3e09ab93cd59fc49f0b>' to 'VisitChildren' 我收到编译器错误C2664 ... cannot convert parameter 2 from 'unittests::UnitTest1::TestBuild::<lambda_b286d160b9bab3e09ab93cd59fc49f0b>' to 'VisitChildren'

If I remove the capture '&' it compiles and works, but I need to capture some bits and bobs. 如果我删除捕获'&'它编译并工作,但我需要捕获一些位和bobs。

Is this possible? 这可能吗?

A closure created by a lambda expression can be implicitly converted to a function pointer, but only if it does not capture any variables. 由lambda表达式创建的闭包可以隐式转换为函数指针,但前提是它不捕获任何变量。 Also, it will be converted to a pointer to an extern "C++" function, not an extern "C" function, and technically those are incompatible types. 此外,它将转换为指向extern "C++"函数的指针,而不是extern "C"函数,从技术上讲,它们是不兼容的类型。

So no, you can't do this. 所以不,你不能这样做。

A hacky workaround is to store your actual closure in a global variable and pass a callback which invokes it. 一个hacky解决方法是将实际闭包存储在全局变量中并传递一个调用它的回调。 This will only work if your program is single-threaded and the DoVisitChildren call does not store the callback for later use. 这仅在您的程序是单线程且DoVisitChildren调用不存储回调供以后使用DoVisitChildren有效。

std::function<void(Option*)> callback;
extern "C" void __cdecl invoke_callback(Option* o) { callback(o); }

// ...

callback = [&] (Option* option) { /* ... */ };
DoVisitChildren(children, invoke_callback);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM