从WebAssembly .wasm模块获取JavaScript导入对象条目 [英] Obtaining JavaScript import object entries from a WebAssembly .wasm module
问题描述
我想了解Rust程序在编译成wasm文件时实际导出的内容,因此我可以为实例化函数提供有效的 importObject
:
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);
据我了解,做到这一点的唯一方法是通过导出类似于s语法的已编译代码文件.我无法在他们的文档中或通过网络搜索找到方法.
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.
推荐答案
您可以使用 wabt 的 wasm2wast
将 .wasm
文件转换为等效的 .wast
.那会满足您的要求.
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.
但是,您不一定需要这样做!JavaScript API为您提供了所需的最多:
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;
}
}
请注意,表和内存的初始/最大值当前是猜测!我建议我们将缺少的信息添加到JS API中.我认为在下一次WebAssembly会议上可能是讨论添加此类内容的好时机.
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.
这篇关于从WebAssembly .wasm模块获取JavaScript导入对象条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!