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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With