1. 程式人生 > >[Rust] Load a WebAssembly Function Written in Rust and Invoke it from JavaScript

[Rust] Load a WebAssembly Function Written in Rust and Invoke it from JavaScript

In this lesson we are going to setup a project from scratch by introducing the JavaScript snippet to load a WebAssembly module. We demonstrate two different ways and showcase the benefit of the streaming solution. Once the module is loaded we can invoke a function previously exported from our Rust code.

 

Create a new project as a library:

cargo new --lib utils

 

Go to the project folder, modify Cargo.toml:

[package]
name = "utils"
version = "0.1.0"
authors = ["zhentian-wan <[email protected]>"]
edition = "2018"

[dependencies]

[lib]
crate-type = ["cdylib"]

 

Create an function in src/lib.rs:

#[no_mangle]
pub extern fn add_one(x: u32) -> u32 {
    x + 1
}

The extern keyword is needed to create an interface, so that this function can be invoked from other languages. The function accepts a value x, which is an unsigned integer, which is incremented by one and returned. In addition, we need to add a no-mangle

 annotation to tell the Rust compiler not to mangle the name of this function.

 

Run:

cargo build --target wasm32-unknown-unknown --release
wasm-gc target/wasm32-unknown-unknown/release/utils.wasm -o utils.gc.wasm

 

Create an index.html file and load utils.gc.wasm file we just generated:

<!DOCTYPE html>
<html>
  <head>
    <script> 
      WebAssembly.instantiateStreaming(fetch("utils.gc.wasm"))
        .then(wasmModule => {
          const result = wasmModeult.instance.exports.add_one(3);
          const text = document.createTextNode(result);
          document.body.appendChild(text);
        });
    </script>
  <head>
  <body></body>
<html>

 

Run:

http

 

Open the broswer we should see the output 4.

Be aware, instantiate streaming requires that our WASM file must be served with a content type, application/wasm. Fortunately, our HTTP server already does so.