javascript 調用WebAssembly的方法
1 windows下安裝emscripten
# 1.克隆emsdk git clone https://github.com/juj/emsdk.git # 2.進入emsdk文件夾 cd emsdk # 3.更新emsdk 這里使用是git所以運行時會提示使用"git pull" ./emsdk update git pull # 4.安裝最新的emsdk 並配置全局的環境變量 這個地方要FQ 而且下載速度很慢 慢慢等吧 大概30分鍾 ./emsdk install --global latest # 5.激活 ./emsdk activate latest # 6.應用環境變量(這個地方要注意 用cmd打開目錄 執行 每次執行emcc 都要執行一下 ./emsdk_env.bat
emcc math.c -Os -s WASM=1 -s SIDE_MODULE=1 -o math.wasm
int add (int x, int y) { return x + y; } int square (int x) { return x * x; }
c語言代碼如上
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1> </h1> <script> /** * @param {String} path wasm 文件路徑 * @param {Object} imports 傳遞到 wasm 代碼中的變量 */ function loadWebAssembly (path, imports = {}) { return fetch(path) // 加載文件 .then(response => response.arrayBuffer()) // 轉成 ArrayBuffer .then(buffer => WebAssembly.compile(buffer)) .then(module => { imports.env = imports.env || {} // 開辟內存空間 imports.env.memoryBase = imports.env.memoryBase || 0 if (!imports.env.memory) { imports.env.memory = new WebAssembly.Memory({ initial: 256 }) } // 創建變量映射表 imports.env.tableBase = imports.env.tableBase || 0 if (!imports.env.table) { // 在 MVP 版本中 element 只能是 "anyfunc" imports.env.table = new WebAssembly.Table({ initial: 0, element: 'anyfunc' }) } // 創建 WebAssembly 實例 return new WebAssembly.Instance(module, imports) }) } //調用 loadWebAssembly('/moban/math.wasm') .then(instance => { const add = instance.exports.add//取出c里面的方法 const square = instance.exports.square//取出c里面的方法 console.log('10 + 20 =', add(10, 20)) console.log('3*3 =', square(3)) console.log('(2 + 5)*2 =', square(add(2 + 5))) }) </script> </body> </html>
經過驗證微信H5支持