是否可以从浏览器控制台运行一些Wasm代码?

时间:2019-05-08 13:03:13

标签: webassembly

我正在阅读以下内容:https://developer.mozilla.org/en-US/docs/WebAssembly/Loading_and_running,他们建议先获取.wasm文件(就像在xhr fetch中一样),然后运行它。

假设我有一小段wasm代码(如this one here转换为.wasm)作为字符串。如何将其粘贴到变量中并在浏览器控制台中运行?

1 个答案:

答案 0 :(得分:2)

下面是一个带有以下WASM代码的示例,该示例导出单个wasm_add函数:

(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)))

例如,您可以使用Python将小的wasm代码转换为整数列表:

f = open('code.wasm','rb')
code_as_integers = [s for s in f.read()]
f.close()
code

得出整数列表,例如

[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]

然后,在浏览器的控制台中键入

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; } )

然后,您将在instance变量中看到导出,并且可以从控制台调用其中的函数,例如

let sum = instance.exports.wasm_add(1,2);