編寫 WebAssembly

AssemblyScript 初體驗

接下來詳細介紹如何使用 AssemblyScript 來編寫 WebAssembly,實現斐波那契序列的計算。 用 TypeScript 實現斐波那契序列計算的模塊 f.ts 以下:html

1
2
3
4
5
6
export function f(x: i32): i32 {
     if (x === 1 || x === 2) {
         return 1;
     }
     return f(x - 1) + f(x - 2)
}

在按照 AssemblyScript 提供的安裝教程成功安裝後, 再經過git

asc f.ts -o f.wasm

就能把以上代碼編譯成可運行的 WebAssembly 模塊。github

爲了加載並執行編譯出的 f.wasm 模塊,須要經過 JS 去加載並調用模塊上的 f 函數,爲此須要如下 JS 代碼:web

1
2
3
4
5
6
fetch('f.wasm') // 網絡加載 f.wasm 文件
     .then(res => res.arrayBuffer()) // 轉成 ArrayBuffer
     .then(WebAssembly.instantiate) // 編譯爲當前 CPU 架構的機器碼 + 實例化
     .then(mod => { // 調用模塊實例上的 f 函數計算
     console.log(mod.instance.f(50));
     });

 

 

[WebAssembly 現狀與實戰](https://www.ibm.com/developerworks/cn/web/wa-lo-webassembly-status-and-reality/index.html)網絡

相關文章
相關標籤/搜索