Define JavaScript static method in C using Duktape

I would like to define a static method on a class. I have the same version using new working fine, I want a static method, thought.

I have tried this:

duk_push_c_function(ctx, call, DUK_VARARGS);
duk_put_prop_string(ctx, -2, "call");
duk_put_prop_string(ctx, -2, "static");
duk_put_global_string(ctx, "JSONRPC2");

When I run:

duk_eval_string_noresult(ctx, "try { print('JSONRPC2 result: ' + JSONRPC2.call()) } catch(e) { print('Error: ' + e) }");

I got:

*** FATAL ERROR: uncaught: ‘invalid stack index -2147483648’

What I am doing wrong?

EDIT: This works:

duk_push_c_function(ctx, jsonrpc_constructor, 0);
duk_push_bare_object(ctx);
duk_push_c_function(ctx, call, DUK_VARARGS);
duk_put_prop_string(ctx, -2, "call");
duk_put_prop_string(ctx, -2, "prototype");
duk_put_global_string(ctx, "JSONRPC1");

duk_eval_string_noresult(ctx, "var rpc = new JSONRPC1; print('JSONRPC1 result: ' + rpc.call())");

ChatGPT give-me the answer

duk_push_object(ctx);
duk_push_c_function(ctx, call, 0);
duk_put_prop_string(ctx, -2, "call");
duk_put_global_string(ctx, "JSONRPC");

Leave a Comment