当前位置:网站首页>第一个WebAssembly程序
第一个WebAssembly程序
2022-07-30 05:43:00 【yunteng521】
前言
WebAssembly/wasm WebAssembly 或者 wasm 是一个可移植、体积小、加载快并且兼容 Web 的全新格式,优势不少,这章讲述用rust 编码 一个 wasm ,html调用
为什么用rust ,参考 https://blog.csdn.net/u012067469/article/details/100100813/
建议,用自己最熟悉的编程语言去编码
浏览器支持 情况 https://developer.mozilla.org/zh-CN/docs/WebAssembly
1:准备
centos7
rust1.55
2:环境搭建
1>rust 安装
根据CPU架构 下载相应的安装文件
https://forge.rust-lang.org/infra/other-installation-methods.html#rustup
2> wasm-pack 安装
https://rustwasm.github.io/docs/book/game-of-life/setup.html
3:创建工程
1>也可以先把模板下下来 git clone https://github.com/rustwasm/wasm-pack-template
2>cargo generate --git ./wasm-pack-template --name test
2>编写代码
mod utils;
use wasm_bindgen::prelude::*;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[wasm_bindgen]
extern {
fn alert(s: &str);
}
#[wasm_bindgen]
pub fn greet() {
alert("Hello, test!");
}
//testcode 开始自己的代码 也就3个函数///
#[wasm_bindgen]
pub fn fib(i: u32) -> u32 {
match i {
0 => 0,
1 => 1,
_ => fib(i-1) + fib(i-2)
}
}
#[wasm_bindgen]
pub fn double(i: u32) -> u32 {
2*i
}
#[wasm_bindgen]
pub fn add(i: u32,j:u32) -> u32 {
i+j
}
3>编译
wasm-pack build 坐等完成
编译完后多了不少文件
这里找到 当前目录 ./pkg/test_bg.wasm 这个文件
4: 测试wasm
1>创建个webdemo

test.html 文件内容
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>IFE JavaScript Task 01</title>
</head>
<body>
<label>请输入要调用的函数名:<input id="aqi-input" type="text"></label>
<br />
<label>请输入函数的参数值:<input id="aqi-input1" type="text"></label>
<br />
<button id="button">确认填写</button>
<div>您输入的值是:<span id="aqi-display">尚无录入</span></div>
<script src="js/testwasm.js"></script>
</script>
</body>
</html>
testwasm.js 内容如下
window.onload = prepare;
function prepare(){
if (!document.getElementById){
return false;
}//检查浏览器是否支持document.getElementById的DOM方法
var submit = document.getElementById("button");
submit.onclick = function(){
clickButton();
}//添加事件处理函数,把onclick事件绑定到ID为"button"元素上
loadwasm1('test_bg.wasm').then(
instance => {
window._wasminstance = instance ;
console.log("wasm load finish");
});
}
function clickButton(){
//let num =loadwasm1('wasm_hello_bg.wasm');
// console.log(num);
// return ;
var output = document.getElementById("aqi-display");
var input = document.getElementById("aqi-input");
var input1 = document.getElementById("aqi-input1");
// text = input.value;//获取ID为"aqi-input"的值
var text1 = "";
if(window._wasminstance){
if(typeof(input.value) == 'string' && typeof(window._wasminstance.exports) == 'object'){
if(!isNaN(input.value)){
//是数字
let number1 = Number(input.value);
switch(number1){
case 1:text1 = window._wasminstance.exports.double(12).toString();break;
case 2:text1 = window._wasminstance.exports.fib(12).toString();break;
case 3:text1 = window._wasminstance.exports.add(12,12).toString();break;
}
}else{
let instr1 = input.value.trim();
let instr2 = input1.value.trim();
let params = instr2.length >0?instr2.split("#"):'';
let func = window._wasminstance.exports[instr1] ;
if (func){
switch(params.length){
case 0: text1 = func(); break;
case 1: text1 = func(Number(params[0])); break;
case 2: text1 = func(Number(params[0]),Number(params[1])); break;
default:
text1 = func();
}
}
}
}
}
output.innerHTML = text1;//把值写入ID为"aqi-display"之中
}
function loadWebAssembly(fileName) {
return fetch(fileName)
.then(response => response.arrayBuffer())
.then(buffer => WebAssembly.compile(buffer))
.then(module => {
return new WebAssembly.Instance(module) });
};
function loadwasm(fileName){
return fetch(fileName).
then(response => response.arrayBuffer()).
then(bufferSource => WebAssembly.instantiate(bufferSource)).
then(result => result.instance.exports.double(2)) ;
};
function loadwasm1(fileName){
return fetch(fileName).
then(response =>response.arrayBuffer()).
then(bytes => WebAssembly.instantiate(bytes)).
then(results => results.instance
);
};
function loadwasm2(fileName,importObject){
return fetch(fileName).
then(response =>response.arrayBuffer()).
then(bytes => WebAssembly.instantiate(bytes,importObject)).
then(results => results.instance
);
};
2>测试 用的是chrome 97 测试的


4: 另外一种方式生成wasm(不用模板)
个人觉得这种更方便点
1>cargo new --lib wasm-hello
2> lib.rs 修改代码
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn fib(i: u32) -> u32 {
match i {
0 => 0,
1 => 1,
_ => fib(i-1) + fib(i-2)
}
}
3>修改 Cargo.toml 增加
[dependencies]
wasm-bindgen="0.2.53"
[lib]
crate-type=["cdylib","rlib"]
4>wasm-pack build
在pkg 查找生成的wasm文件
5:如需工程代码后续在上传
上一张wasm 文件内容(273B 够小吧)
wasm文件内容
边栏推荐
- 【调优】一个 Spark 任务某天突然变慢怎么解决
- Servlet basic principles and application of common API methods
- 【十年网络安全工程师整理】—100渗透测试工具使用方法介绍
- 3分钟告诉你如何成为一名黑客|零基础到黑客入门指南,你只需要掌握这五点能力
- 批量自动归集
- vulnhub-XXE ctf security question
- Operators and Interaction Basics
- phpok website vulnerability exploitation analysis
- uncategorized SQLException; SQL state [null]; error code [0]; sql injection violation, syntax error
- 【MySQL功法】第5话 · SQL单表查询
猜你喜欢

c#下Web3合约空投、转账调用代码

Online sql editing query tool sql-editor

Servlet basic principles and application of common API methods

FastAPI Quick Start

JDBC programming of MySQL database

SQL Server安装教程

MYSQL一站式学习,看完即学完

3 minutes to tell you how to become a hacker | Zero foundation to hacker introductory guide, you only need to master these five skills

3分钟告诉你如何成为一名黑客|零基础到黑客入门指南,你只需要掌握这五点能力

Using PyQt5 to add an interface to YoloV5 (1)
随机推荐
uni-app使用npm命令安装组件
Flink CDC 实现Postgres到MySQL流式加工传输案例
《MySQL高级篇》四、索引的存储结构
Function 函数式接口及应用
冒泡排序、选择排序、插入排序、快速排序
POI工具类
【十年网络安全工程师整理】—100渗透测试工具使用方法介绍
C#下利用开源NPlot绘制股票十字交叉线
Invalid bound statement (not found)出现的原因和解决方法
sql concat()函数
Arthas 命令解析(jvm/thread/stack/heapdump)
The operations engineer interview experience
【SQL】SQL 高频面试题英语版(1)
批量自动归集
FastAPI Quick Start
Detailed introduction to the usage of Nacos configuration center
mysql is not an internal or external command, nor is it a runnable program or batch file to resolve
Usage of exists in sql
jsonpath
Redis 发布/订阅