Reputation: 10591
I'm reading this: https://developer.mozilla.org/en-US/docs/WebAssembly/Loading_and_running, and they propose to fetch (as in xhr fetch) the .wasm
file first, and run it.
Let's say I have a small piece of wasm code (like this one here converted into .wasm
) as a string. How can I paste it in a variable and run it in my browser console?
Upvotes: 1
Views: 592
Reputation: 5243
Here's an example, with the following WASM code, that exports a single wasm_add
function:
(module
(type $t0 (func (param i32 i32) (result i32)))
(func $wasm_add (type $t0) (param $p0 i32) (param $p1 i32) (result i32)
get_local $p1
get_local $p0
i32.add)
(table $T0 0 anyfunc)
(memory $memory 1)
(export "memory" (memory 0))
(export "wasm_add" (func $wasm_add)))
You can convert your small wasm code to a list of integers, for instance, using Python:
f = open('code.wasm','rb')
code_as_integers = [s for s in f.read()]
f.close()
code
Results in a list of integers such as
[0, 97, 115, 109, 1, 0, 0, 0, 1, 135, 128, 128, 128, 0, 1, 96, 2, 127, 127, 1, 127, 3, 130, 128, 128, 128, 0, 1, 0, 4, 132, 128, 128, 128, 0, 1, 112, 0, 0, 5, 131, 128, 128, 128, 0, 1, 0, 1, 6, 129, 128, 128, 128, 0, 0, 7, 149, 128, 128, 128, 0, 2, 6, 109, 101, 109, 111, 114, 121, 2, 0, 8, 119, 97, 115, 109, 95, 97, 100, 100, 0, 0, 10, 141, 128, 128, 128, 0, 1, 135, 128, 128, 128, 0, 0, 32, 1, 32, 0, 106, 11]
Then, in the browser's console type
wasmCode = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 135, 128, 128, 128, 0, 1, 96, 2, 127, 127, 1,
127, 3, 130, 128, 128, 128, 0, 1, 0, 4, 132, 128, 128, 128, 0, 1, 112, 0, 0, 5, 131, 128, 128, 128, 0, 1,
0, 1, 6, 129, 128, 128, 128, 0, 0, 7, 149, 128, 128, 128, 0, 2, 6, 109, 101, 109, 111, 114, 121, 2, 0, 8,
119, 97, 115, 109, 95, 97, 100, 100, 0, 0, 10, 141, 128, 128, 128, 0, 1, 135, 128, 128, 128, 0, 0, 32, 1,
32, 0, 106, 11])
let instance;
WebAssembly.instantiate(wasmCode).then( ( module ) => { instance = module.instance; } )
Then, you'll see your exports in the instance
variable and you can invoke functions in it from the console, such as
let sum = instance.exports.wasm_add(1,2);
Upvotes: 4