Calling a C callback function from C++ via a lambda -
i have code in plain c static library:
extern "c" { typedef void (__cdecl* visitchildren)(option*); void __cdecl dovisitchildren(children* list, visitchildren visitor); }
and i'm trying use c++ code (unit tests) using lambda.
... dovisitchildren(children, [&] (option* option) { ... });
i'm getting compiler error c2664 ... cannot convert parameter 2 'unittests::unittest1::testbuild::<lambda_b286d160b9bab3e09ab93cd59fc49f0b>' 'visitchildren'
if remove capture '&' compiles , works, need capture bits , bobs.
is possible?
a closure created lambda expression can implicitly converted function pointer, if not capture variables. also, converted pointer extern "c++"
function, not extern "c"
function, , technically incompatible types.
so no, can't this.
a hacky workaround store actual closure in global variable , pass callback invokes it. work if program single-threaded , dovisitchildren
call not store callback later use.
std::function<void(option*)> callback; extern "c" void __cdecl invoke_callback(option* o) { callback(o); } // ... callback = [&] (option* option) { /* ... */ }; dovisitchildren(children, invoke_callback);
Comments
Post a Comment