Hello World with Rust and Webassembly

A WASM-code possible to write different ways. Exist excelent application EMScripten that convert  code from C++ or Rust to WASM, but in Rust enviroment possible convert Rust-code with help wasm32-unknown-unknown compiler. 

In this Article I'll show simple example "Hello World" on the Rust and how to run this code with help Flask webframework.

cargo init

change file Cargo.toml

[package]
name = "helloworld"
version = "0.1.0"
authors = ["Your Name <info@arahna.de>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

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

[dependencies]
wasm-bindgen = "0.2"

Writing a code in file src/lib.rs:

use wasm_bindgen::prelude::*;

// take two integer values and return a + b
#[wasm_bindgen]
pub fn call_me_from_javascript(a: i32, b: i32) -> i32 {
  return a + b;
}

#[wasm_bindgen]
extern "C" {
    fn alert(s: &str);
}

// js alert
#[wasm_bindgen]
pub fn alert_window() {
    alert("Hello World!");
}

Run command in terminal:

wasm-pack build --target web

this command creates a folder pkg, essentially this folder destined for creating node-application, but I won’t use node-app, I’ll using python micro framework Flask. So, we create Flask-app with the following structure:

helloworld

  - __init__.py

  - hello.py

  templates

      -index.html

  static

    js

       -index.js

       -helloworld.js

    wasm

         -helloworld_bg.wasm

where:

helloworld.js and helloworld_bg.wasm files from folder pkg

the file index.js will be like this:

import init from "/static/js/helloworld.js";

const runWasm = async () => {

  const helloWorld = await init("/static/wasm/helloworld_bg.wasm");

  const Result_1 = helloWorld.call_me_from_javascript(9, 2);
      
  const Result_2 = helloWorld.alert_window();
  
  var div_1 = document.getElementById("1");

  div_1.textContent = Result_1;

};
runWasm();

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World - Rust</title>
    
  </head>
<body>
  <div id="1"></div>
  <div id="2"></div>
</body>
<script type="module" src="/static/js/index.js"></script>
</html>

hello.py:

from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route("/")
def hello():
    return render_template('index.html')

if __name__ == "__main__":
    app.run()

run the flask application and look at the page http://127.0.0.1:5000/

and on the page number 11

The number 11 is obtained because we call the wasm function from javascript call_me_from_javascript() and pass two values to this function 9 and 2. WASM function adds these two values and returns the result 11. This is very convenient when you need to get the result of complex calculations, which can slow down the site, in such case the task of computing can be assigned to WASM.

2020-05-26

Post your comment

Search
Popular Posts
Subscribe
{{post}}