This very simple and minimal tutorial documents in a few easy steps how to play with WebAssembly (WASM) and get first results within minutes.
While the code below is mostly useless, it will show, how to call the alert
function from within a WASM file and thus demonstrate how to import and export DOM objects.
Of course, this exercise has no real use. It is just meant to show, that getting started with WASM isn't hard. And there is no need for a complex build-chain, tons of tools or a dedicated VMs. Just use a browser, one online tool and that's it.
To execute the code shown below, we need a very modern browser. WASM likely needs to be enabled via configuration flag. We tested on Chrome Version 52.0.2741.0 Canary and activated chrome://flags/#enable-webassembly
. Same for Firefox 49.0a1 with javascript.options.wasm: true
.
We need nothing else but the browser, one HTML file and a WASM file. We can use the amazing tool linked below to generate the WASM file for us - from WAST. No complex build chain needed:
Create an HTML file using the following source code:
<script>
/* An XHR fetching the WASM file as ArrayBuffer */
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.onload = ready;
xhr.open('GET', 'test.wasm');
xhr.send(null);
/* Execute once the file was fetched */
function ready() {
var info = {
foo: {bar: alert} // "import" the alert method
};
var a = Wasm.instantiateModule(
new Uint8Array(xhr.response), info
).exports;
a.f(); // execute the f method, that is foo.bar()
}
</script>
Now, let's create some WAST code to feed to the tool linked above and generate a WASM for for us (test.wasm
, as referenced in the HTML):
(module ;; start the module
(import "foo" "bar") ;; import foo.bar
(func $bar (call_import 0 )) ;; map bar()
(export "f" 0) ;; export bar()
)
Click "Download", grab the resulting WASM file, place it in the same folder as your HTML file, open the HTML in Chrome or any WASM-compatible browser of choice, see the alert pop. Done :) Why? Because why not!
alert
from wasmThis HTML runs a wasm module that imports and calls
alert
. TheUint8Array
contains the binary version of the wasm module below:Module that imports a JS external function and calls it with an integer argument:
How to
In order to translate the S-expression text format files (.wast) into binary (.wasm) we can use the WebAssembly Binary Toolkit:
The generated binary file is passed as a
BufferArray
to the WebAssembly JS API in order to compile/load modules. And this is how it looks like (145 bytes vs 772 bytes in text format):LLVM also has experimental support for a WebAssembly backend (compile it with
LLVM_EXPERIMENTAL_TARGETS_TO_BUILD=WebAssembly
). So we can compile C/C++ into LLVM's IR, and then into .wast:Links