使用 WebAssembly 调用 Web API 方法

Using WebAssembly to call Web API methods

是否可以使用Web APIs with WebAssembly? If so, how? I'm more interested in the Navigator interface.

是的,有可能。

如何在使用 WebAssembly 工具链时 调用 JavaScript APIs 取决于特定的工具链。它实际上是 FFI 的一种形式:从 C++ 代码看,您似乎在调用外部函数,但工具链连接到嵌入器(此处为浏览器的 JavaScript)。几个例子:

Emscripten 等工具链自动为 WebAssembly.instantiate 生成 importObject(以及 .html.js 文件)/因此,大多数内部 WebAssembly 细节通常是隐藏的(我在下面记录了它们)。

此设计允许您调用任何 JavaScript 代码,而不仅仅是 JavaScript API。因此,您可以从 WebAssembly 调用自己的 JavaScript 代码。工具链只是让处理常见的 web API 集变得更容易,有时以跨平台的方式,例如SDL2 处理音频、键盘、鼠标、操纵杆和图形。

内部细节

WebAssembly 的 JavaScript API allows you to pass an importObjectWebAssembly.Instantiate 构造函数和 WebAssembly.instantiate 函数:

new Instance(moduleObject [, importObject])

Promise<{module:WebAssembly.Module, instance:WebAssembly.Instance}>
    instantiate(BufferSource bytes [, importObject])

WebAssembly binary format contains an import section where you (through a compiler such as LLVM) declare the imports which it'll use. Each of these imported fields is looked up in the importObject, and the functions can be invoked 通过 WebAssembly 的 callcall_indirect 操作码。

因此您可以调用任意 JavaScript,这又可以调用您想要的任何网络 API。将来,WebAssembly 可能 gain capabilities which allow the embedder expose APIs directly,在浏览器中嵌入这可能包括 DOM、canvas、事件等