编写 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)网络

相关文章
相关标签/搜索