[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.css

 

Create a new project as a library:html

cargo new --lib utils

 

Go to the project folder, modify Cargo.toml:app

[package]
name = "utils"
version = "0.1.0"
authors = ["zhentian-wan <answer881215@gmail.com>"]
edition = "2018"

[dependencies]

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

 

Create an function in src/lib.rs:less

#[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.fetch

 

Run:ui

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

<!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:spa

http

 

Open the broswer we should see the output 4.code

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.server

相關文章
相關標籤/搜索