JavaScript Interoperation

Importing and Exporting JS Functions

From the Rust Side

When using wasm within a JS host, importing and exporting functions from theRust side is straightforward: it works very similarly to C.

WebAssembly modules declare a sequence of imports, each with a module name_and an _import name. The module name for an extern { … } block can bespecified using #[link(wasm_import_module)], currentlyit defaults to "env".

Exports have only a single name. In addition to any extern functions theWebAssembly instance's default linear memory is exported as "memory".

  1. # #![allow(unused_variables)]
  2. #fn main() {
  3. // import a JS function called `foo` from the module `mod`
  4. #[link(wasm_import_module = "mod")]
  5. extern { fn foo(); }
  6. // export a Rust function called `bar`
  7. #[no_mangle]
  8. pub extern fn bar() { /* ... */ }
  9. #}

Because of wasm's limited value types, these functions must operate only onprimitive numeric types.

From the JS Side

Within JS, a wasm binary turns into an ES6 module. It must be _instantiated_with linear memory and have a set of JS functions matching the expectedimports. The details of instantiation are available on MDN.

The resulting ES6 module will contain all of the functions exported from Rust, nowavailable as JS functions.

Here is a very simple example of the whole setup in action.

Going Beyond Numerics

When using wasm within JS, there is a sharp split between the wasm module'smemory and the JS memory:

  • Each wasm module has a linear memory (described at the top of this document),which is initialized during instantiation. JS code can freely read and writeto this memory.

  • By contrast, wasm code has no direct access to JS objects.

Thus, sophisticated interop happens in two main ways:

  • Copying in or out binary data to the wasm memory. For example, this is one wayto provide an owned String to the Rust side.

  • Setting up an explicit "heap" of JS objects which are then given"addresses". This allows wasm code to refer to JS objects indirectly (usingintegers), and operate on those objects by invoking imported JS functions.

Fortunately, this interop story is very amenable to treatment through a generic"bindgen"-style framework: wasm-bindgen. The framework makes it possible towrite idiomatic Rust function signatures that map to idiomatic JS functions,automatically.

Custom Sections

Custom sections allow embedding named arbitrary data into a wasm module. Thesection data is set at compile time and is read directly from the wasm module,it cannot be modified at runtime.

In Rust, custom sections are static arrays ([T; size]) exposed with the#[link_section] attribute:

  1. # #![allow(unused_variables)]
  2. #fn main() {
  3. #[link_section = "hello"]
  4. pub static SECTION: [u8; 24] = *b"This is a custom section";
  5. #}

This adds a custom section named hello to the wasm file, the rust variablename SECTION is arbitrary, changing it wouldn't alter the behaviour. Thecontents are bytes of text here but could be any arbitrary data.

The custom sections can be read on the JS side using theWebAssembly.Module.customSections function, it takes a wasm Module and thesection name as arguments and returns an Array of ArrayBuffers. Multiplesections may be specified using the same name, in which case they will allappear in this array.

  1. WebAssembly.compileStreaming(fetch("sections.wasm"))
  2. .then(mod => {
  3. const sections = WebAssembly.Module.customSections(mod, "hello");
  4. const decoder = new TextDecoder();
  5. const text = decoder.decode(sections[0]);
  6. console.log(text); // -> "This is a custom section"
  7. });