
- WebAssembly 教程
- WebAssembly - 首頁
- WebAssembly - 概述
- WebAssembly - 簡介
- WebAssembly - WASM
- WebAssembly - 安裝
- WebAssembly - 編譯為 WASM 的工具
- WebAssembly - 程式結構
- WebAssembly - JavaScript
- WebAssembly - JavaScript API
- WebAssembly - 在 Firefox 中除錯 WASM
- WebAssembly - “你好,世界”
- WebAssembly - 模組
- WebAssembly - 驗證
- WebAssembly - 文字格式
- WebAssembly - 將 WAT 轉換為 WASM
- WebAssembly - 動態連結
- WebAssembly - 安全
- WebAssembly - 與 C 合作
- WebAssembly - 與 C++ 合作
- WebAssembly - 與 Rust 合作
- WebAssembly - 與 Go 合作
- WebAssembly - 與 Node.js 合作
- WebAssembly - 示例
- WebAssembly 有用資源
- WebAssembly - 快速指南
- WebAssembly - 有用資源
- WebAssembly - 討論
WebAssembly - 與 Node.js 合作
JavaScript 有一堆可與 wasm 程式碼一同使用的 API。該 API 也在 node.js 中受支援。
在系統中安裝 NODEJS。建立一個 Factorialtest.js 檔案。
讓我們使用 C++ 階乘程式碼,如下所示 −
int fact(int n) { if ((n==0)||(n==1)) return 1; else return n*fact(n-1); }
開啟 WebAssembly Explorer,其可在 https://mbebenita.github.io/WasmExplorer/ 中獲得,如下所示 −

第一列有 C++ 階乘函式,第二列有 WebAssembly 文字格式,最後一列有 x86 彙編程式碼。
WebAssembly 文字格式如下 −
(module (table 0 anyfunc) (memory $0 1) (export "memory" (memory $0)) (export "_Z4facti" (func $_Z4facti)) (func $_Z4facti (; 0 ;) (param $0 i32) (result i32) (local $1 i32) (set_local $1(i32.const 1)) (block $label$0 (br_if $label$0 (i32.eq (i32.or (get_local $0) (i32.const 1) ) (i32.const 1) ) ) (set_local $1 (i32.const 1) ) (loop $label$1 (set_local $1 (i32.mul (get_local $0) (get_local $1) ) ) (br_if $label$1 (i32.ne (i32.or (tee_local $0 (i32.add (get_local $0) (i32.const -1) ) ) (i32.const 1) ) (i32.const 1) ) ) ) ) (get_local $1) ) )
C++ 函式 fact 已在 WebAssembly 文字格式中匯出為 “_Z4facti”。
Factorialtest.js
const fs = require('fs'); const buf = fs.readFileSync('./factorial.wasm'); const lib = WebAssembly.instantiate(new Uint8Array(buf)). then(res => { for (var i=1;i<=10;i++) { console.log("The factorial of "+i+" = "+res.instance.exports._Z4facti(i)) } } );
在命令列中,執行命令 node factorialtest.js,輸出如下 −
C:\wasmnode>node factorialtest.js The factorial of 1 = 1 The factorial of 2 = 2 The factorial of 3 = 6 The factorial of 4 = 24 The factorial of 5 = 120 The factorial of 6 = 720 The factorial of 7 = 5040 The factorial of 8 = 40320 The factorial of 9 = 362880 The factorial of 10 = 3628800
廣告