webassembly WASM入门:将c++编译为wasm并运行
WASM的优点是,通过使用比等效的JavaScript代码低得多的程序表示形式(二进制格式),它的运行速度要快得多,从而实现接近本机的性能。点击下载得到.wasm文件。然后编译为对象,即可调用对象中的方法。
·
WASM的优点是,通过使用比等效的JavaScript代码低得多的程序表示形式(二进制格式),它的运行速度要快得多,从而实现接近本机的性能。
- c++实现:
#include <iostream>
using namespace std;
int Fibonaccisequence(int n)
{
if(n == 1 || n == 2)
{
return 1;
}
else
{
return Fibonaccisequence(n-1) + Fibonaccisequence(n-2);
}
}
// 将以上部分放到在线编译中即可
int main()
{
int n; //n表示为第几个数值
for(n=1;n<=7;n++)
{
int res = Fibonaccisequence(n);
cout << res <<endl;
}
return 0;
}
- https://mbebenita.github.io/WasmExplorer/
点击下载得到.wasm文件。
- 将以下代码放入html中的< script >即可
1.将wasm文件转为ArrayBuffer
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 每个字符占用2个字节
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
然后编译为对象,即可调用对象中的方法
WebAssembly.instantiate(bytes)
- 官方的方法
fetch('test.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes)
).then(results => {
// Do something with the compiled results!
});
参考
添加链接描述
加载和运行 WebAssembly 代码
添加链接描述
WebAssembly 软解 HEVC 在 B 站的实践
更多推荐
所有评论(0)