Rust & WebAssembly minimal cargo project

03 Dec 2017 0 Comments

Lets create wasm module from cargo project.

Cargo project

Creation

cargo new simple_cargo_project --bin
cd simple_cargo_project

Files creation

Create new files in src folder.
  • lib.rs
  • mod_1.rs
  • mod_2.rs

Code insertion


extern crate simple_cargo_project;

fn main() { }

pub mod mod_1;
pub mod mod_2;

#[no_mangle]
pub fn add_one_from_mod_1(x: i32) -> i32 {
    x + 1
}

#[no_mangle]
pub fn add_two_from_mod_1(x: i32) -> i32 {
    x + 2
}

#[no_mangle]
pub fn add_three_from_mod_2(x: i32) -> i32 {
    x + 3
}

#[no_mangle]
pub fn add_four_from_mod_2(x: i32) -> i32 {
    x + 4
}

Files tree of simple_cargo_project folder

.
├── Cargo.toml
└── src
    ├── lib.rs
    ├── main.rs
    ├── mod_1.rs
    └── mod_2.rs

Wasm module generation
rustup run nightly cargo build --release --target wasm32-unknown-unknown
wasm-gc target\wasm32-unknown-unknown\release\simple_cargo_project.wasm simple_cargo_project.wasm
Now we have simple_cargo_project.wasm module in root folder. You can download wasm module here.

Wasm module connection

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebAssembly</title>
    <script src="script.js"></script>
</head>
<body>

</body>
</html>

window.onload = function() {
    window.Module = {};

    fetch('simple_cargo_project.wasm')
    .then(response => response.arrayBuffer())
    .then(bytes => WebAssembly.instantiate(bytes, {}))
    .then(results => {
        Module.exports = results.instance.exports;
        
        Object.getOwnPropertyNames(Module.exports)
        .forEach((property) => {
            if (typeof Module.exports[property] === 'function')
            console.log(property);
        });
    });
};

  • add_one_from_mod_1
  • add_two_from_mod_1
  • add_three_from_mod_2
  • add_four_from_mod_2
All functions are available in Module.export object.
let res = Module.exports.add_three_from_mod_2(6); // res = 9