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

Is it possible to run some Wasm code from the browser console?

我正在读这个:https://developer.mozilla.org/en-US/docs/WebAssembly/Loading_and_running,他们建议先获取(如在 xhr 获取中).wasm 文件,然后 运行 它。

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

这是一个示例,使用以下 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)))

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

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