0

好的,所以基本上我有一个很长的对象数组,我需要以数组作为参数多次调用 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();它会按预期工作,并且102444都会被打印出来。

4

1 回答 1

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 处的数组。

于 2017-07-12T20:28:33.030 回答