好的,所以基本上我有很多对象,我需要多次调用一个JavaScript函数,并将数组作为参数。我每次调用函数时重新创建列表时都已经工作了,但是将数组移动到Duktape堆栈顶部的尝试并没有按预期工作。也许我在完全错误的轨道上......
duk_context* ctx(duk_create_heap_default());
duk_push_c_function(ctx, nativePrint, DUK_VARARGS);
duk_put_global_string(ctx, "print");
/// Define the function the first time
duk_eval_string(ctx, "function func(entries, targetEntry) { print(targetEntry, JSON.stringify(entries)); return 404; }");
duk_get_global_string(ctx, "func");
/// Define lambdas to create the array
auto pushObject = [&] () {
duk_idx_t obj_idx;
obj_idx = duk_push_object(ctx);
duk_push_int(ctx, 42);
duk_put_prop_string(ctx, obj_idx, "meaningOfLife");
};
auto pushArray = [&] () {
duk_idx_t arr_idx;
arr_idx = duk_push_array(ctx);
pushObject();
duk_put_prop_index(ctx, arr_idx, 0);
pushObject();
duk_put_prop_index(ctx, arr_idx, 1);
return arr_idx;
};
/// Push the arguments
auto arr_idx = pushArray();
duk_push_number(ctx, 102);
/// Define lambda to call the function
auto processEntry = [&] () {
if (duk_pcall(ctx, 2 /*nargs*/) != 0) {
printf("Error: %s\n", duk_safe_to_string(ctx, -1));
} else {
if (duk_is_number(ctx, -1)) cout << "NumRes: " << duk_get_number(ctx, -1) << endl;
else printf("Res: %s\n", duk_safe_to_string(ctx, -1));
}
duk_pop(ctx);
cout << endl;
};
/// Calling the function the first time
processEntry();
/// Loading the function as the global string again
duk_eval_string(ctx, "function func(entries, targetEntry) { print(targetEntry, JSON.stringify(entries)); return 404; }");
duk_get_global_string(ctx, "func");
/// Attempt to move the array to the top and execute the function
/// Executing pushArray(); again works but not duk_swap_top(...);
// pushArray();
duk_swap_top(ctx, arr_idx);
duk_push_number(ctx, 444);
processEntry();
如您所见,在最底部我尝试调用duk_swap_top(ctx, arr_idx)
以将阵列移动到顶部。显然,它没有按照我的想法行事,而是返回 TypeError: undefined not callable
。将其替换为另一个pushArray();
时,它会按预期工作,并且 102 和 444 会被打印出来。
答案 0 :(得分:0)
在我看来,你正在将数组和'102'推送到值堆栈:
[ ... array 102 ]
然后调用duk_pcall()来消耗参数(nargs = 2)并推送结果:
[ ... result ]
然后弹出结果。调用后,数组不再位于值堆栈中。
有多种方法可以构建代码,但您可以先注册'func'并创建数组,然后对每个调用使用以下序列(包括第一个):
duk_get_global_string(ctx, "func");
duk_dup(ctx, arr_idx); /* duplicate array reference */
duk_push_uint(ctx, 1234); /* additional argument, varies? */
rc = duk_pcall(ctx, 2);
/* inspect result */
duk_pop(ctx);
这会在调用之间保留arr_idx处的数组。