Last active
July 6, 2017 15:38
-
-
Save DmitrySoshnikov/384a272c98048edb7a07f7fc3dccb327 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Wasm</title> | |
</head> | |
<body> | |
<script> | |
(async () => { | |
/** | |
* Binary code for the following WASM program in s-expression format: | |
* | |
* (module | |
* (export "sqrt" (func $sqrt)) | |
* (func $sqrt | |
* (param $num f32) | |
* (result f32) | |
* | |
* (f32.sqrt (get_local $num)) | |
* ) | |
* ) | |
* | |
* Can also assemble a binary from the s-expression format, and then | |
* load it as: | |
* | |
* const wasm = await fetch('./test.wasm'); | |
* const bytes = await wasm.arrayBuffer(); | |
* | |
* Initial byte sequence `0x00, 0x61, 0x73, 0x6d` is the | |
* `\0asm` WebAssembly magic number. | |
*/ | |
const bytes = new Int8Array([ | |
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x86, | |
0x80, 0x80, 0x80, 0x00, 0x01, 0x60, 0x01, 0x7d, 0x01, 0x7d, | |
0x03, 0x82, 0x80, 0x80, 0x80, 0x00, 0x01, 0x00, 0x06, 0x81, | |
0x80, 0x80, 0x80, 0x00, 0x00, 0x07, 0x88, 0x80, 0x80, 0x80, | |
0x00, 0x01, 0x04, 0x73, 0x71, 0x72, 0x74, 0x00, 0x00, 0x0a, | |
0x8b, 0x80, 0x80, 0x80, 0x00, 0x01, 0x85, 0x80, 0x80, 0x80, | |
0x00, 0x00, 0x20, 0x00, 0x91, 0x0b | |
]); | |
const module = await WebAssembly.compile(bytes); | |
const instance = await WebAssembly.instantiate(module); | |
const {sqrt} = instance.exports; | |
console.log('Hello from WASM binary! sqrt(4) =', sqrt(4)); // 2 | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment