是否可以从它在 JavaScript 中导入的主机函数之一访问 WebAssembly 实例的导出内存?

Is it possible to access a WebAssembly instance's exported memory from one of the host functions it imports in JavaScript?

我一直在手写一些 WebAssembly 模块以了解它们的工作原理。现在我正在尝试了解导入和导出的工作原理,以及如何执行 IO。

模块如下:

(module
  (import "env" "print_string" (func $print_string (param i32)))

  (func $main (result i32)
    i32.const 1024
    call $print_string

    i32.const 0
  )

  (memory $memory 2)
  (data (i32.const 1024) "example[=11=]")

  (export "memory" (memory $memory))
  (export "main" (func $main))
)

到目前为止,我一直在使用 wasmtime (which is a WebAssembly API written in Rust) to run this module. With wasmtime, I can instantiate a Linker which will take care of wrapping the print_string function coming from the host that I pass to the module. The wrapped print_string function has access to an extra Caller 参数,它允许我检查实例化的模块导出、获取内存并从中读取以 null 结尾的字符串。这使我既可以导出内存,又可以访问导入函数中实例化模块的内存。

这在 WebAssembly 的 JavaScript API 中可能吗?我正在查看 API 可用 here,但似乎没有任何迹象表明这是可能的。

我在 JavaScript API 中看到的唯一解决方案是:模块不从模块导出内存,而是从主机导入内存。这样导入的函数也可以访问内存对象。理想情况下,我希望模块导出自己的内存。

至少在Javascript你可以做一些像

new Uint8Array(wasmInstance.exports.memory.buffer)

访问您导出为字节数组的整个内存。 例如,我使用它来将内存的第一个字节导出到 canvas

  var wasmModule = new WebAssembly.Module(bytes);
  var wasmInstance = new WebAssembly.Instance(wasmModule,{
    gfx: {
      flip: function() {
        imageData.data.set(new Uint8Array(wasmInstance.exports.mem.buffer,0,canvasWidth*canvasHeight*4));
        ctx.putImageData(imageData, 0, 0);
      }
    }
  });
  wasmInstance.exports.init();

你可以在这里看到整个演示: http://worlddominationcommittee.org/~lee/filez/wasm/test5.html