webassembly WASM入门:将c++编译为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)
  1. 官方的方法
fetch('test.wasm').then(response =>
  response.arrayBuffer()
).then(bytes =>
  WebAssembly.instantiate(bytes)
).then(results => {
  // Do something with the compiled results!
});

参考

添加链接描述
加载和运行 WebAssembly 代码
添加链接描述

WebAssembly 软解 HEVC 在 B 站的实践

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值