lambdas with duktape (using C++)

huangapple go评论61阅读模式
英文:

lambdas with duktape (using C++)

问题

我想使用在C++中定义的lambda函数调用duk_push_c_function(),类似于以下方式:

SomeObjType parameter;
// 在 'parameter' 中存储内容
auto myLambda = [parameter](duk_context* ctx) {
  // 对 'parameter' 执行操作
  return (duk_ret_t)1;
}

duk_push_c_function(ctx, myLambda , 1);

我的问题是这样不会编译,因为myLambda不是C函数:

error C2664: 'duk_idx_t duk_push_c_function(duk_context *,duk_c_function,duk_idx_t)': 无法将参数 2 从 'MyObjectName::<lambda_07f401c134676d14b7ddd718ad05fbe6>' 转换为 'duk_c_function'

有没有一种简洁的方法将带参数的无名称函数传递给Duktape?

英文:

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

SomeObjType parameter;
// store stuff in &#39;parameter&#39;
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: &#39;duk_idx_t duk_push_c_function(duk_context *,duk_c_function,duk_idx_t)&#39;: cannot convert argument 2 from &#39;MyObjectName::&lt;lambda_07f401c134676d14b7ddd718ad05fbe6&gt;&#39; to &#39;duk_c_function&#39;

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

答案1

得分: 3

duk_push_c_function() 期望一个纯C风格的函数指针。非捕获 lambda 可以衰变成这样的指针,但捕获 lambda 不能。因此,您需要将指向您的 parameter 的指针存储在一个存储区中,以便您的 lambda 可以访问它:

存储区允许C代码存储内部状态,这些状态可以安全地与ECMAScript代码隔离开来。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月14日 07:10:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定