好的,所以基本上我有一个很长的对象数组,我需要以数组作为参数多次调用 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都会被打印出来。