3

Using the duktape javascript implementation, you can expose native C functions to javascript and implement them like this:

static duk_ret_t native_prime_check(duk_context *ctx) {
   int arg1 = duk_require_int(ctx, 0);
   int arg2 = duk_require_int(ctx, 1);
   // do something.
   return 0;
}

When exposing the native function we need to specify the number of arguments.

duk_push_c_function(ctx, native_prime_check, 2 /*nargs*/);

Please give an example of how to make a C function that takes a variable number of arguments and expose it to Javascript using duktape.

Steve Hanov
  • 11,316
  • 16
  • 62
  • 69

1 Answers1

7

When you push a C function you can also give DUK_VARARGS as the argument count. When you do that, the value stack will contain call arguments directly, with duk_get_top(ctx) giving you the number of arguments given:

static duk_ret_t dump_args(duk_context *ctx) {
    duk_idx_t i, nargs;
    nargs = duk_get_top(ctx);
    for (i = 0; i < nargs; i++) {
        printf("type of argument %d: %d\n", (int) i, (int) duk_get_type(ctx, i));
    }
}

duk_push_c_function(ctx, dump_args, DUK_VARARGS);
Sami Vaarala
  • 606
  • 4
  • 5
  • In the case of async callback such setInterval(callback, delay, arg1, arg2,..) how do i get a reference to the args. Do you provide a kind of copy function to keep it somewhere in c memory (saveCtx(..) restoreCtx(..)) and reuse at each call ?? if not do i need to process each of the params separatly, using the duk_inspect_value to get informations and then call the appropriate duk_get_XXX ??? – Guillaume Pelletier Mar 27 '17 at 17:39
  • Assuming the arguments are to be stored for an eventual callback, they would normally be copied to an array stored with the other callback state (e.g. the callback function reference itself). There's no pack/unpack API at present so you'd need to duk_push_array() and copy the values into the array one at a time. – Sami Vaarala Mar 27 '17 at 22:12