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 對象包含已經(jīng)由瀏覽器編譯的無狀態(tài) WebAssembly 代碼,
可以高效地與 Workers 共享、緩存在 IndexedDB 中,和多次實例化。
WebAssembly.Module() 構(gòu)造函數(shù)可以用來同步編譯給定的 WebAssembly 二進制代碼。
不過,獲取 Module 對象的主要方法是通過異步編譯函數(shù),如 WebAssembly.compile(),
或者是通過 IndexedDB 讀取 Module 對象。
3. WebAssembly.Instance
WebAssembly.Instance 對象是WebAssembly.Module實例化后的結(jié)果,它的有狀態(tài)的,可執(zhí)行的。
WebAssembly.Instance對象中包含了所有WebAssembly模塊中導(dǎo)出的方法(Exported WebAssembly functions),這些方法可以直接在JavaScript中調(diào)用,
可以通過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