Getting JavaScript import object records from WebAssembly.wasm module

I want to understand what Rust actually exports when it is compiled into a wasm file, so I can provide a valid one importObjectfor the instance function:

WebAssembly.instantiate(bufferSource, importObject);

As far as I understand, the only way to do this is to export s-syntax, such as a compiled code file. I cannot find how to do this in my documents or through a web search.

+2
source share
1 answer

You can use a tool like wabt wasm2wast to translate a file .wasminto an equivalent .wast. This will do what you ask.

! API JavaScript , :

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;
    }
}

, / ! , JS API. , WebAssembly .

+3

Source: https://habr.com/ru/post/1683008/


All Articles