-1

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Peter
  • 1
  • 1
  • 7
    A lambda is not a `c_function`. A non-capturing lambda can decay into a plain function pointer but not a capturing one. – NathanOliver Feb 13 '23 at 23:17

1 Answers1

3

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770