WebAssembly: From Concept to Application - A Comprehensive Guide

by Gautham Pai

WebAssembly (Wasm) is a powerful technology that brings near-native performance to web applications. This guide will walk you through the process of creating, compiling, and running WebAssembly code using various methods.

1. The WebAssembly Text Format (WAT)

Let's start with a simple addition function in WebAssembly Text Format (WAT):

(module
  (func $add (param $lhs i32) (param $rhs i32) (result i32)
    local.get $lhs
    local.get $rhs
    i32.add)
  (export "add" (func $add))
)

This WAT code defines a module with an add function that takes two 32-bit integer parameters and returns their sum.

2. Compiling WAT to Wasm

To use our WAT code in a browser, we need to compile it to the binary Wasm format. We can do this using the WebAssembly Binary Toolkit (WABT):

sudo apt install wabt
wat2wasm math.wat -o math.wasm

This command installs WABT and uses the wat2wasm tool to compile our math.wat file into math.wasm.

3. Using WebAssembly in the Browser

Now that we have our Wasm file, we can use it in a web page:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Simple add example</title>
</head>
<body>
  <script>
    WebAssembly.instantiateStreaming(fetch("math.wasm"))
      .then(obj => {
        console.log(obj.instance.exports.add(1, 2));  // "3"
      });
  </script>
</body>
</html>

This HTML file loads our math.wasm module and calls its add function with arguments 1 and 2, logging the result (3) to the console.

4. Running WebAssembly with Python

We can also run our WebAssembly module using Python with the wasmtime library:

pip install wasmtime

Create a Python script (runner.py) with the following content:

from wasmtime import Store, Module, Instance
store = Store()
module = Module.from_file(store.engine, 'math.wat')
instance = Instance(store, module, [])
add = instance.exports(store)['add']
print("add(2, 3) = %d" % add(store, 2, 3))

Run it with:

python3 runner.py

This script loads our WAT file directly, creates an instance of the module, and calls the add function with arguments 2 and 3.

5. Using Wasmtime Command-Line Tool

Wasmtime is a standalone runtime for WebAssembly. You can install and use it from the command line:

curl https://wasmtime.dev/install.sh -sSf | bash
wasmtime --invoke add math.wat 1 2

This installs Wasmtime and runs our add function directly from the WAT file with arguments 1 and 2.

6. Integrating WebAssembly in a Bash Script

Finally, let's look at how we can use our WebAssembly module in a Bash script:

#!/bin/bash
function add() {
  # Cast to number; default = 0
  local x=$(($1))
  local y=$(($2))
  local result=$(wasmtime --invoke add math.wat $x $y 2>/dev/null)
  echo "$result"
}

# main
for num in "27 6" "6 27" "42 12"; do
  set -- $num
  echo "add($1, $2) = $(add "$1" "$2")"
done

This script defines an add function that uses Wasmtime to call our WebAssembly add function. It then demonstrates the usage with a few example inputs.

Conclusion

WebAssembly provides a powerful way to run high-performance code in various environments. We've seen how to write WebAssembly code in WAT format, compile it to Wasm, and run it using different methods:

  1. In a web browser using JavaScript
  2. With Python using the wasmtime library
  3. Directly from the command line with the Wasmtime runtime
  4. Integrated into a Bash script

This versatility makes WebAssembly a valuable tool for developers looking to optimize performance-critical parts of their applications across different platforms.

Test Your Knowledge

No quiz available

Tags