lambdas with duktape (using C++)

95 Views Asked by At

I want to call duk_push_c_function() with a lambda defined in C++, a bit like this:

SomeObjType parameter;
// store stuff in 'parameter'
auto myLambda = [parameter](duk_context* ctx) {
  // do stuff with parameter
  return (duk_ret_t)1;
}

duk_push_c_function(ctx, myLambda , 1);

My problem is that this won't compile because myLambda is not a C function:

error C2664: 'duk_idx_t duk_push_c_function(duk_context *,duk_c_function,duk_idx_t)': cannot convert argument 2 from 'MyObjectName::<lambda_07f401c134676d14b7ddd718ad05fbe6>' to 'duk_c_function'

Is there a nice way of passing a nameless function with parameters into duktape?

1

There are 1 best solutions below

0
Remy Lebeau On

duk_push_c_function() expects a plain C-style function pointer. A non-capturing lambda can decay into such a pointer, but a capturing lambda cannot. So, you will have to store a pointer to your parameter in a stash where your lambda can reach it:

Stashes allow C code to store internal state which can be safely isolated from ECMAScript code.