在javascript中导入WebAssembly模块的正确方法是什么

问题描述 投票:0回答:2

在web assembly.org,JS API页面,在javascript中导入WebAssembly的方法是

fetch('example.wasm').then(response => response.arrayBuffer())
.then(bytes => instantiate(bytes, importObject))
.then(instance => instance.exports.e());

emcc发出的js文件似乎就是这样做的。

但是当我对 Rust 的 Cargo 使用 wasm-pack 时,javascript 文件只是做

import * as wasm from './example.wasm'

这两者有什么区别?直接导入是新支持的功能吗?当使用直接导入时,我如何从 javascript 访问 WebAssembly 的内存,因为我没有像使用第一种方法那样将它们传递给 WebAssembly 模块?

javascript emscripten webassembly
2个回答
3
投票

WebAssembly 模块的声明式导入尚未标准化。我假设 wasm-pack 的目标是 Node.js 的实验性导入功能:http://web.archive.org/web/20220528033110/https://www.joyent.com/blog/improved-wasm-support-coming-到节点#importing-web assembly-modules

如何访问内存取决于模块:如果导出它,您可以作为成员访问它,如果导入它,它必须作为 ES6 模块的成员以您在导入中使用的名称提供对象。


0
投票

根据平台的不同,如果 wasm 模块在 Web 浏览器中运行,请按照相关提及获取并实例化。当在 Nodejs 中运行 WASM 时,WASI 甚至可以提供文件系统沙箱。它可以使用 WASI 实例化中使用节点 Fs 从磁盘读取文件

    const importObject = { wasi_snapshot_preview1: wasi.wasiImport };
    const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm'));
    const instance = await WebAssembly.instantiate(wasm, importObject);
    wasi.start(instance);

链接:https://nodejs.org/api/wasi.html

© www.soinside.com 2019 - 2024. All rights reserved.