Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a native javascript function taking a variable number of arguments using duktape?

Tags:

duktape

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.

like image 240
Steve Hanov Avatar asked Feb 08 '23 22:02

Steve Hanov


1 Answers

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);
like image 116
Sami Vaarala Avatar answered Jun 15 '23 19:06

Sami Vaarala