当前位置:网站首页>The first WebAssembly program
The first WebAssembly program
2022-07-30 06:54:00 【yunteng521】
前言
WebAssembly/wasm WebAssembly 或者 wasm 是一个可移植、体积小、加载快并且兼容 Web 的全新格式,There are many advantages,This chapter tells aboutrust 编码 一个 wasm ,html调用
为什么用rust ,参考 https://blog.csdn.net/u012067469/article/details/100100813/
建议,Code in the programming language you are most familiar with
浏览器支持 情况 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>You can also download the template first 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 Start your own code 也就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 坐等完成
After compiling, there are many more files
这里找到 当前目录 ./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>Please enter the name of the function to call:<input id="aqi-input" type="text"></label>
<br />
<label>Please enter parameter values for the function:<input id="aqi-input1" type="text"></label>
<br />
<button id="button">Confirm to fill in</button>
<div>您输入的值是:<span id="aqi-display">No entry yet</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(不用模板)
Personally I think this is more convenient
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:If you need the project code, upload it later
上一张wasm 文件内容(273B 够小吧)
wasm文件内容
边栏推荐
猜你喜欢
misc-file steganography of CTF

2022CISCNmisc

Flink-流/批/OLAP一体得到Flink引擎

torch distributed training

FastAPI Quick Start

C#利用开源NPlot实现K线图(蜡烛图)
Misc of CTF-Memory Analysis (Volatility)

Using PyQt5 to add an interface to YoloV5 (1)

Communication middleware Fast DDS basic concepts and communication examples

SQL Server 数据库之生成与执行 SQL 脚本
随机推荐
Arrays工具类的使用
misc-log analysis of CTF
C#中对委托的理解和使用
《MySQL高级篇》四、索引的存储结构
Remember a Mailpress plugin RCE vulnerability recurrence
根据ip地址获取地理位置及坐标(离线方式)
史上超强最常用SQL语句大全
MySQL - 多表查询与案例详解
CTFSHOW command execution [web29-web124] unfinished to be continued
[Net Ding Cup 2020 Qinglong Group] AreUSerialz
【小程序项目开发-- 京东商城】uni-app之分类导航区域
Misc of CTF-image steganography
uni-app使用npm命令安装组件
awd --waf deployment
CTF misc-audio and video steganography
Redis 客户端常见异常分析
Operators and Interaction Basics
mysql delete duplicate data in the table, (retain only one row)
Invalid bound statement (not found)出现的原因和解决方法
【面经】米哈游数据开发面经