Skip to content

Instantly share code, notes, and snippets.

@david-pm
Created June 5, 2018 02:32
Show Gist options
  • Save david-pm/ed7f014ee3a7686fcf4ff9ee640ef0a3 to your computer and use it in GitHub Desktop.
Save david-pm/ed7f014ee3a7686fcf4ff9ee640ef0a3 to your computer and use it in GitHub Desktop.
A wat2wasm tutorial
INSTALL:
$ git clone --recursive https://github.com/WebAssembly/wabt
$ cd wabt
$ make clang-release
$ cd out/clang/Release
$ pwd | pbcopy (or just pwd and copy the output manually)
Add the pwd path to your shell config $PATH for ease of use.
now you have a:
$ wat2wasm
... executable
PROJECT:
-----------------------------------------------
Makefile
--
build:
wat2wasm main.wat -v -o main.wasm
serve:
python -m SimpleHTTPServer 8080
-----------------------------------------------
index.html
--
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>hello wasm</title>
</head>
<body>
<h1>_</h1>
<script src="main.js"></script>
</body>
</html>
-----------------------------------------------
main.wat
--
(module
(memory (export "my_memory") 1)
(data (i32.const 0) "hello wasm")
(global (export "length") i32 (i32.const 10))
(global (export "position") i32 (i32.const 0))
)
-----------------------------------------------
main.js
--
function main(wasm) {
const mem = wasm.exports.my_memory
const size = wasm.exports.length
const pos = wasm.exports.position
const bytes = new Uint8Array(mem.buffer, pos, size)
const str = new TextDecoder('utf8').decode(bytes)
let h1 = document.querySelector('h1')
h1.innerHTML = 'loading your wasm module...'
setTimeout(() =>
h1.innerHTML = str, 2000
)
}
fetch('main.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, {})
).then(result =>
result.instance
).then(main);
--------------------------------------------------------------------
Now compile and run it:
$ make
$ make serve
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment