0

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

ijustlovemath
  • 703
  • 10
  • 21
  • 1
    Q: Is it possible to call C functions from JS using the QuickJS engine? A: Sure. Just expose your functions from a C-language QuickJS module: https://calbertts.medium.com/writing-native-modules-in-c-for-quickjs-engine-49043587f2e2. Is it possible to call C functions *WITHOUT* using a module? A: No, probably not. It would probably be unwise, even if you found a "clever hack". Q: Why do you want to do this? – paulsm4 Nov 14 '22 at 22:17
  • You misread the question. I want to call JS functions from C, not the other way around. The purpose is to embed the functionality of a NodeJS script in a native library. I got it working though, see the linked code. – ijustlovemath Nov 18 '22 at 11:01

0 Answers0