1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | func $src/asm/module/f (param f64) (result f64) (local i32) get_local 0 f64.const 1 f64.eq tee_local 1 if i32 get_local 1 else get_local 0 f64.const 2 f64.eq end i32.const 1 i32.and if f64.const 1 return end get_local 0 f64.const 1 f64.sub call 0 get_local 0 f64.const 2 f64.sub call 0 f64.add end |
1 2 3 | WebAssembly.instantiate(bytes).then(mod=>{ mod.instance.f(50); }) |
1 2 3 4 5 6 7 | WebAssembly.instantiate(bytes,{ window:{ alert:window.alert } }).then(mod=>{ mod.instance.f(50); }) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // 声明从外部导入的模块类型 declare namespace window { export function alert(v: number): void; } function _f(x: number): number { if (x == 1 || x == 2) { return 1; } return _f(x - 1) + _f(x - 2) } export function f(x: number): void { // 直接调用 JS 模块 window.alert(_f(x)); } |
1 2 3 4 5 6 | (import "window" "alert" (func $src/asm/module/window.alert (type 0))) (func $src/asm/module/f (type 0) (param f64) get_local 0 call $src/asm/module/_f call $src/asm/module/window.alert) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | const fs = require('fs'); function toUint8Array(buf) { var u = new Uint8Array(buf.length); for (var i = 0; i < buf.length; ++i) { u = buf; } return u; } function loadWebAssembly(filename, imports) { // 读取 wasm 文件,并转换成 byte 数组 const buffer = toUint8Array(fs.readFileSync(filename)); // 编译 wasm 字节码到机器码 return WebAssembly.compile(buffer) .then(module => { // 实例化模块 return new WebAssembly.Instance(module, imports) }) } loadWebAssembly('../temp/assembly/module.wasm') .then(instance => { // 调用 f 函数计算 console.log(instance.exports.f(10)) }); |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |