crossbind
GitHub

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.

src/main.js
import { initNative, Native } from './native/native.h';
 
await initNative();
console.log(await Native.sample());

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.

src/main.js
import { initNative, Matrix } from './native/Matrix.h';
import { Uuid } from 'cargo:uuid';
import { zlibVersion } from 'conan:zlib/zlib.h';
 
await initNative();

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.

src/index.mjs
import initNative from '../dist/my-app-wasm-wasm32-st-release.node.js';
 
const { Native } = await initNative();
console.log(Native.sample());

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.
Defaulttrue where Worker exists, 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.
Defaulttrue in an mt browser build, false in an st one
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.
Defaultconsole.debug with a wasm stdout: prefix
errorHandler(text, 'stderr') => void
Receives each line written to stderr.
Defaultconsole.error with a wasm 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.mjs passes 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
Function options do not cross into a worker
With 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.
Defaultdata/ 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::vector as 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:

src/main.js
import { initNative, Matrix } from './native/Matrix.h';
 
await initNative();
 
const a = await new Matrix(1210000, 1);
const result = await a.multiple(await new Matrix(1210000, 2));
console.log(await result.get(0));
useWorker: falseuseWorker: true
A call returnsthe valuea promise of it
new X(...) returnsthe instancea promise: write await new X(...)
A returned std::vectora vector objecta plain array
A JavaScript function passed to C++workscannot cross into the worker
Function options of initNativeapplyignored
A path under /opfsthrowsworks 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:

src/main.js
const m = await initNative({
useWorker: false,
logHandler: (text) => myLogger.info(`[wasm] ${text}`),
errorHandler: (text) => myLogger.error(`[wasm] ${text}`),
});

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.

src/index.mjs
const m = await initNative({
env: { TMPDIR: '_CROSSBIND_DATA_PATH_/scratch' },
});

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):

shell
npm install -D @crossbind/typescript-config@beta
tsconfig.json
{ "extends": "@crossbind/typescript-config" }

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: true in crossbind.config.js does nothing: runtime options go to initNative().
  • x.method is not a function in a browser usually means a new X() whose promise was never awaited.
  • m.GDALVersionInfo is not a function (or crossbind: GDALVersionInfo is not bound in the native module in 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 /opfs path while fs.opfs is 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 no mt.

Full reference: init.md and lifecycle-and-types.md.

Type to search every guide page and section.
↑↓ navigate↵ openesc close