Expand description
The host session: what makes a C function callable from a script qjs is running.
§The problem this solves
When qjs -m test_fib.js runs fib(10), the call arrives in a C function whose first act
is JS_ToInt32(ctx, &n, argv[0]). That call needs a JSContext * and, behind it, the
interpreter that is executing the script. The engine is inside Interp::run_script while
this happens, and a program that never asked the C API for anything has never published
that interpreter — so the C function receives a null context and answers JS_EXCEPTION
for no stated reason.
session is the fix: for the duration of a script or module run, the interpreter is
published (through the same thread-local a C callback uses) along with a context that
stands for it. Everything a .so module does then works exactly as it does inside an
embedding that called JS_NewContext.
§Why one session per thread
A class id lives in a module’s static data and is registered against a runtime, so the
runtime has to be the same object for every native import in the process — a fresh one per
import would hand a module a different JSRuntime * each time. One thread-local session
per thread matches how the reference’s JSRuntime is per-process, and keeps the CLI free
of any lifetime plumbing.
§Why a guard rather than a callback
The obvious shape is enter(ctx, || ctx.eval(src)), and it does not compile: the borrow
of ctx that produces the interpreter pointer and the borrow the closure needs are the
same one. A guard splits them — the borrow ends when session returns, and the guard
holds raw pointers that are valid because the interpreter lives in the Context and does
not move.
Structs§
- Session
Guard - Keeps an interpreter published for as long as it lives.
Functions§
- runtime_
ptr - The runtime native modules register their classes against.
- session
- Publish
context’s interpreter for the C API until the returned guard is dropped.