txiki.js icon indicating copy to clipboard operation
txiki.js copied to clipboard

RPC-FFI-like interop when embedding into a shared library

Open brandonros opened this issue 4 years ago • 3 comments

mildly related to https://github.com/saghul/txiki.js/pull/179/files

image

It's pretty clear that TJS_Run is most likely a blocking call. That's fine. You can get around that by putting TJS on its own thread.

My question to you is, how could the native calling code (for example a Win32 DLL in DllMain) interact with the TJS runtime? How could messages be passed to and from? Obviously you can do things like named pipes, shared memory, a queue, etc. but I'm looking if it's possible to inject events.

struct TJSRuntime {
    TJSRunOptions options;
    JSRuntime *rt;
    JSContext *ctx;

Is there any easy way to pass messages from the QuickJS runtime/context into native code, and back from native code into QuickJS runtime?

brandonros avatar Oct 09 '21 23:10 brandonros

I see with tjs__bootstrap_globals I have some options like EventTarget. I'm also wondering if I can do something like window.addEventListener.

$ ./build/tjs 
Welcome to txiki.js — The tiny JavaScript runtime
Type "\h" for help
> window.addEventListener('foo', (event) => console.log(event))
undefined
> window.dispatchEvent(new Event('foo'))
{ isTrusted: false }
true

brandonros avatar Oct 09 '21 23:10 brandonros

Looks like from C I can pass an event like this:

/* Emit window 'load' event. */
    if (!JS_IsException(ret) && is_main) {
        static char emit_window_load[] = "window.dispatchEvent(new Event('load'));";
        JSValue ret1 = JS_Eval(ctx, emit_window_load, strlen(emit_window_load), "<global>", JS_EVAL_TYPE_GLOBAL);
        if (JS_IsException(ret1)) {
            tjs_dump_error(ctx);
        }
    }

Now to find how to call C from JS.

Most likely going to need to compile tjs executable as a shared library instead too...

brandonros avatar Oct 09 '21 23:10 brandonros

TBH I never considered this use case so far.

The whole thing is not thread safe, so we'd need to add some new API to make is possible to call stuff from outside the thread running.

saghul avatar Oct 11 '21 06:10 saghul