使用 WebAssembly 调用 Web API 方法 [英] Using WebAssembly to call Web API methods

查看:53
本文介绍了使用 WebAssembly 调用 Web API 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将 Web API 与 WebAssembly 一起使用?如果是这样,如何?我对导航器界面更感兴趣.

Is it possible to use Web APIs with WebAssembly? If so, how? I'm more interested in the Navigator interface.

推荐答案

是的,这是可能的.

如何在使用 WebAssembly 工具链时调用 JavaScript API 取决于该特定工具链.它实际上是 FFI 的一种形式:从 C++ 代码看来,您正在调用一个外部函数,但工具链桥接到嵌入器(这里是浏览器的 JavaScript).几个例子:

How to do call JavaScript APIs when using a WebAssembly toolchain is up to that specific toolchain. It's effectively a form of FFI: from C++ code it looks like you're calling an external function, but the toolchain bridges to the embedder (here, the browser's JavaScript). A few examples:

诸如 Emscripten 之类的工具链会为 WebAssembly.instantiate(连同 .html.js 自动生成一个 importObject> 文件)/因此,大多数内部 WebAssembly 细节通常是隐藏的(我在下面记录了它们).

Toolchains such as Emscripten automatically generate an importObject for WebAssembly.instantiate (along with .html and .js files)/ Most of the internal WebAssembly details are therefore usually hidden (I document them below).

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

This design allows you to call any JavaScript code, not just JavaScript APIs. You can therefore call your own JavaScript code from WebAssembly. Toolchains simply make it easier to handle common sets of web APIs, sometimes in a cross-platform manner, e.g. SDL2 does audio, keyboard, mouse, joystick, and graphics.

WebAssembly 的 JavaScript API 允许您通过 一个 importObjectWebAssembly.实例化构造函数和WebAssembly.instantiate函数:

WebAssembly's JavaScript API allows you to pass an importObject to the WebAssembly.Instantiate constructor and the WebAssembly.instantiate function:

new Instance(moduleObject [, importObject])

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

WebAssembly 二进制格式包含一个import section 在这里你(通过一个编译器,比如 LLVM)声明它的导入会用.每个导入的字段都在 importObject 中查找,函数 可以通过 WebAssembly 的 callcall_indirect 操作码调用.

The 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 through WebAssembly's call and call_indirect opcode.

因此,您可以调用任意 JavaScript,而后者又可以调用您想要的任何 Web API.将来,WebAssembly 可能会获得允许嵌入器直接公开 API 的功能,在浏览器中嵌入这可以包括 DOM、画布、事件等.

You can therefore call arbitrary JavaScript, which in turn can call any web API you want. In the future, WebAssembly may gain capabilities which allow the embedder expose APIs directly, in a browser embedding this could include the DOM, canvas, events, etc.

这篇关于使用 WebAssembly 调用 Web API 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆