Obtaining JavaScript import object entries from a WebAssembly .wasm module

痞子三分冷 提交于 2019-12-10 18:38:46

问题


I want to understand what a Rust program actually exports when it is compiled to a wasm file so I can provide a valid importObject to the instantiate function:

WebAssembly.instantiate(bufferSource, importObject);

As far as I understand, the only way to do this is by exporting an s-syntax like file of the compiled code. I can't find how to do this in their docs or through web searches.


回答1:


You can use a tool such as wabt's wasm2wast to translate a .wasm file to the equivalent .wast. That would do what you ask for.

However, you don't necessarily need to do this! The JavaScript API gives you most of what you want:

let arrayBuffer = ...; // Somehow get your .wasm file into an ArrayBuffer. XHR, from a string, or what have you.
let module = WebAssembly.Module(arrayBuffer); // This is the synchronous API! Only use it for testing / offline things.

let importObject = {};
for (let imp of WebAssembly.Module.imports(module)) {
    if (typeof importObject[imp.module] === "undefined")
        importObject[imp.module] = {};
    switch (imp.kind) {
    case "function": importObject[imp.module][imp.name] = () => {}; break;
    case "table": importObject[imp.module][imp.name] = new WebAssembly.Table({ initial: ???, maximum: ???, element: "anyfunc" }); break;
    case "memory": importObject[imp.module][imp.name] = new WebAssembly.Memory({ initial: ??? }); break;
    case "global": importObject[imp.module][imp.name] = 0; break;
    }
}

Note that Table and Memory initial / maximum are currently guesses! I'm proposing that we add the missing information to the JS API. I think at the next WebAssembly meeting may be a good time to discuss such an addition.



来源:https://stackoverflow.com/questions/44444050/obtaining-javascript-import-object-entries-from-a-webassembly-wasm-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!