Skip to content

Instantly share code, notes, and snippets.

@dduan
Created December 29, 2017 04:13
Show Gist options
  • Save dduan/e3a348ff28c4d0c4a1278b8229116eb3 to your computer and use it in GitHub Desktop.
Save dduan/e3a348ff28c4d0c4a1278b8229116eb3 to your computer and use it in GitHub Desktop.
"Hello, World!" In WebAssembly
(module
(memory (export "memory") 1)
(data (i32.const 0) "Hello, world!")
(global (export "length") i32 (i32.const 12))
(global (export "position") i32 (i32.const 0)))
compile:
wat2wasm main.wat -o main.wasm
serve:
python -m SimpleHTTPServer
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="play.js"></script>
</body>
</html>
function main(wasm) {
const memory = wasm.exports.memory;
const length = wasm.exports.length;
const position = wasm.exports.position;
const bytes = new Uint8Array(memory.buffer, position, length);
const s = new TextDecoder('utf8').decode(bytes);
console.log(s);
}
fetch("main.wasm").then(reponse =>
reponse.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, {})
).then(result =>
result.instance
).then(main);
@A1rPun
Copy link

A1rPun commented May 11, 2021

This gist helped me getting started. Noticed the length was one short.

  (global (export "length") i32 (i32.const 13))

@komodoooo
Copy link

That's the power of science.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment