1. 从bufferSource到WebAssembly.Module
WebAssembly.compile()的用法如下,
Promise<WebAssembly.Module> WebAssembly.compile(bufferSource);
它会将bufferSource编译为一个包含WebAssembly.Module对象的Promise。
其中,bufferSource可以是一个包含二进制代码(.wasm模块)的 typed array 或 ArrayBuffer。
例子,
async function f(){
const response = await fetch('simple.wasm');
const bufferSource = response.arrayBuffer();
const mod = await WebAssembly.compile(bufferSource); // 将bufferSource编译为module
}
2. WebAssembly.Module
WebAssembly.Module 对象包含已经由浏览器编译的无状态 WebAssembly 代码,
可以高效地与 Workers 共享、缓存在 IndexedDB 中,和多次实例化。
WebAssembly.Module() 构造函数可以用来同步编译给定的 WebAssembly 二进制代码。
不过,获取 Module 对象的主要方法是通过异步编译函数,如 WebAssembly.compile(),
或者是通过 IndexedDB 读取 Module 对象。
3. WebAssembly.Instance
WebAssembly.Instance 对象是WebAssembly.Module实例化后的结果,它的有状态的,可执行的。
WebAssembly.Instance对象中包含了所有WebAssembly模块中导出的方法(Exported WebAssembly functions),这些方法可以直接在JavaScript中调用,
可以通过WebAssembly.Instance的exports方法来获取。
例如,
const importObject = {
imports: {
imported_func(arg) {
console.log(arg);
}
}
};
async function f(){
const response = await fetch('simple.wasm');
const bufferSource = await response.arrayBuffer();
const result = await WebAssembly.instantiate(bufferSource, importObject);
const {instance:{exports}} = result;
exports.exported_func();
}
f();
WebAssembly.Instance()方法可以同步将一个WebAssembly.Module对象实例化,
但是,获取 Instance 对象的主要方法是使用 WebAssembly.instantiateStreaming()方法,或者WebAssembly.instantiate()方法,它们都会返回一个Promise。
参考
MDN: WebAssembly.compile()
MDN: WebAssembly.Module
NDN: WebAssembly.Instance