Is it possible to call CommonJS module functions from C using QuickJS?

299 views Asked by At

Note, this is different than this question, which only concerns functions and not module functions.


I have a module I have built by converting a NodeJS script to a CommonJS module using esbuild. I'd like to access the functions within that module from a C or C++ library, using QuickJS. The goal is (eventually) to automatically build a native library for a popular open source NodeJS application, without having to manually patch it.

For simple functions, you can do something like so:

    /* assume ctx has a valid JSContext */
    const char * code = "function foo (input) { return input + 3; }";
    JSValue result = JS_Eval(ctx, code, strlen(code), "<input>", JS_EVAL_TYPE_GLOBAL);
    
    // some error checking...
    JSValue global = JS_GetGlobalObject(ctx);
    JSValue foo = JS_GetPropertyStr(ctx, global, "foo");
    JSValue arg = JS_NewInt32(ctx, 5);
    JSValue args[] = {arg};
    result = JS_Call(ctx, foo, global, 1, args);
    int32_t res;
    JS_ToInt32(ctx, &res, result);
    printf("foo(5) = %"PRIi32"\n", res); // prints "foo(5) = 8"

However, if you have a module, nothing enters global scope, so you can't access any module level functions.

Is there any way to accomplish this?

Here's the code: https://github.com/ijustlovemath/determine-basal-native/blob/main/lib/dbasal.c

0

There are 0 answers