Using WebAssembly to call Web API methods

后端 未结 1 1395
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 05:52

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

相关标签:
1条回答
  • 2020-12-15 06:15

    Yes, it is possible.

    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:

    • C++ with Emscripten
    • SDL2
    • html5.h
    • OpenGL / WebGL / OpenGL ES / OpenGL ES 2.0
    • Unity scripting

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

    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.

    Internal Details

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

    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.

    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.

    0 讨论(0)
提交回复
热议问题