編寫 WebAssembly


AssemblyScript 初體驗

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

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 提供的安裝教程成功安裝后, 再通過

asc f.ts -o f.wasm

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

為了加載並執行編譯出的 f.wasm 模塊,需要通過 JS 去加載並調用模塊上的 f 函數,為此需要以下 JS 代碼:

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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM