Runtime API
initNative() starts the native runtime and resolves to the module. Every generated module exports it, and one call serves every native import of the app. Its options are runtime choices: crossbind.config.js does not reach it, apart from the build's env.
The 30-second model
At build time, crossbind build (or your bundler plugin) compiles the native code as crossbind.config.js says. At run time, your app calls initNative() once; when it resolves, every binding is ready.
Named imports are null until the promise resolves. A module imported after the runtime started is bound as soon as it loads.
Where it comes from
With a bundler plugin, import it from any header, .rs file, cargo: crate or conan: header you already import: they all export the same function. The first call starts the runtime and binds every imported module. Later calls resolve to the same module and ignore their options.
Without a bundler, import the built loader from the output folder (paths.output, dist here) and call its default export. Node.js and edge builds also write an ES module per runtime that exports initNative and every bound name: node/wasm.mjs, node/napi.mjs and edge/wasm.mjs. On a plain page, a <script> tag with the browser loader defines a global initNative.
Options
The wasm runtimes (browser, Node.js and edge) take the same options with different defaults. A runtime ignores an option it has no use for.
useWorkerboolean- Browser: runs the module in a Web Worker, so every call returns a promise (worker mode). OPFS needs it.
- Default
truewhereWorkerexists, as in every browser workerUrlstring- Browser, worker mode: the script the worker starts from.
- Defaultthe loader script
fs.opfsboolean- Browser: mounts the Origin Private File System at
/opfs, inside the worker only. See Files. - Default
truein anmtbrowser build,falsein anstone envobject of strings- Environment variables of the native process, merged over the build's.
_CROSSBIND_DATA_PATH_in a value becomes the data folder. - Defaultthe build's
env logHandler(text, 'stdout') => void- Receives each line the C++ writes to stdout.
- Default
console.debugwith awasm stdout:prefix errorHandler(text, 'stderr') => void- Receives each line written to stderr.
- Default
console.errorwith awasm stderr:prefix onRuntimeInitialized(m) => void- Runs once the runtime is ready, before the promise resolves.
getWasmFunction() => WebAssembly.Module- Instantiates a module you already hold instead of fetching the
.wasm. Edge runtimes need it;dist/edge/wasm.mjspasses it for you. pathstring- Where the loader finds its
.wasm, data and worker files: a URL, a root path or a path relative to the page. - Defaultthe bundler's base;
/on a plain page; the loader's folder in Node.js paths{ wasm, data, js, worker }- File names under
path. A bundler plugin sets them itself and ignores yours. - Defaultthe build's file names
useWorker: true, logHandler, errorHandler, onRuntimeInitialized and getWasmFunction are ignored: a function cannot be sent to a worker, so the worker logs with the default prefixes. Pass useWorker: false when you need them.A Node-API addon (-e node on a desktop platform) takes three options:
env- Environment variables. A value passed here replaces the process's own; a value from the build never does.
addonPath- Where the addon is.
- Defaultnext to the loader, or in its platform package
dataPath- The data folder. It cannot change once the addon has started.
- Default
data/next to the loader
On React Native, initNative() takes no options; the build's env applies.
The module
The promise resolves to the module: the bound classes, functions, enums and constants (the same values the named imports get), plus these helpers:
toArray(vector)- Returns a bound
std::vectoras an array. Every runtime. toVector(Vector, array)- Returns an array as a bound vector; takes the class or its name. Every runtime.
FS- The Emscripten virtual filesystem, in memory on the edge. Wasm builds only: browser, Node.js and edge.
getFileBytes(path),getFileList(start?)- A file as a
Uint8Array; a recursive[{ path, size }]listing. Browser and Node.js wasm builds. getDefaultPath(),getFinalPath(path),getRandomPath(start?),autoMountFiles(files, parent?)- OPFS and in-memory mounts, and files the user picked; see Files. Browser only.
Where C++ takes a std::vector, a plain array converts on every call in worker mode. Elsewhere it converts only for functions and constructors, so pass toVector(...) to a method.
A module that binds a pointer also exports the pointer helpers (cstring, allocBuffer, readBuffer and the rest); see C++. Every header module also exports AllSymbols, the started module itself; importing it binds every function of that header.
A C++ exception thrown by a call reaches JavaScript as an Error; see Exceptions.
Worker mode
In a browser the module runs in a Web Worker unless you pass useWorker: false. Every call, every new and every value you read, constants and fields included, then returns a promise:
| useWorker: false | useWorker: true | |
|---|---|---|
| A call returns | the value | a promise of it |
new X(...) returns | the instance | a promise: write await new X(...) |
A returned std::vector | a vector object | a plain array |
| A JavaScript function passed to C++ | works | cannot cross into the worker |
Function options of initNative | apply | ignored |
A path under /opfs | throws | works while fs.opfs is on and the browser supports OPFS |
Set dts: 'promise' in crossbind.config.js so the generated types return promises too.
initNative.terminate() stops the worker, and the calls it has not answered reject with an AbortError: that is how a page stops a call that is still running. The next initNative() starts a fresh one.
Logging and environment
By default, stdout lines go to console.debug and stderr lines to console.error, prefixed wasm stdout: and wasm stderr:. To send them to your own logger, keep the module on the page thread:
Runtime env values are strings, merged over the env the build declares in targetSpecs (Data files). _CROSSBIND_DATA_PATH_ in a value becomes the data folder: /crossbind in the browser and on the edge, data/ next to the loader in Node.js.
Object lifetime
A C++ object is freed when the garbage collector reclaims its handle, at a time you do not control. That holds in the browser, in Node.js and in React Native 0.88 and later. .delete() frees it at once: call it when an object holds a file, a socket or a lot of memory, and on objects made in a loop. On React Native before 0.88, .delete() is the only way.
An object or memory a library returns through a raw pointer stays the library's: free it with the library's own function.
In browser and Node.js wasm builds, initNative.terminate() drops the module (and stops the worker in worker mode), so the next initNative() starts a new one. A Node-API addon cannot be unloaded: the next call resolves the same module, its native state intact.
TypeScript
crossbind writes declarations for every native import under .crossbind/types/, .crossbind/rust-crates/types/ and .crossbind/conan/types/. Install the shared config and extend it once (TypeScript 5.5 or later):
From a C++ header, classes get typed constructors, fields and methods; other names are any, and initNative returns Promise<unknown>. In worker mode, set dts: 'promise' so every generated return type is a Promise. Constructors stay typed as synchronous, since TypeScript has no async constructor: write await new X() anyway.
Common pitfalls
useWorker: trueincrossbind.config.jsdoes nothing: runtime options go toinitNative().x.method is not a functionin a browser usually means anew X()whose promise was never awaited.m.GDALVersionInfo is not a function(orcrossbind: GDALVersionInfo is not bound in the native modulein a worker): a function of a dependency's header you reach only through the module needs a named import too; see What a library header binds.- Mounting
/opfs/...from the page thread throws, and so does any/opfspath whilefs.opfsis off. runtime: 'mt'works in the dev server but fails in production when the host does not send the COOP/COEP headers; see Threads and workers.- Edge runtimes have no Web Workers: no
useWorker, no OPFS and nomt.
Full reference: init.md and lifecycle-and-types.md.