Rust开发WASM,浏览器运行WASM

首先需要安装wasm-pack

复制代码
cargo install wasm-pack

使用cargo创建工程

复制代码
cargo new --lib mywasm

编辑Cargo.toml文件,修改lib的类型为cdylib,并且添加依赖wasm-bindgen

复制代码
[package]
name = "mywasm"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = "0.2"

修改代码lib.rs

复制代码
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn add(n1: usize, n2: usize) -> usize {
    n1 + n2
}

编译lib.rs生成wasm

复制代码
wasm-pack build --target web

下载wasm-bindgen的过程大概需要10分钟,请耐心等待。

接下来创建文件index.html,使用wasm

复制代码
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>wasm web demo</title>
  </head>
  <body>
    <script type="module">
      import init, {add} from "./pkg/mywasm.js";
      init().then(() => {
          console.log("add(1,2) = " + add(1, 2))
        });
      </script>
  </body>
</html>

启动测试用web server

复制代码
python3 -m http.server 8000

打开chrome访问http://localhost:8000,并且打开调试控制台,可以看到运行结果。

相关推荐
DongLi016 小时前
rustlings 学习笔记 -- exercises/05_vecs
rust
郑州光合科技余经理1 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1231 天前
matlab画图工具
开发语言·matlab
dustcell.1 天前
haproxy七层代理
java·开发语言·前端
norlan_jame1 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone1 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054961 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月1 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
番茄灭世神1 天前
Rust学习笔记第2篇
rust·编程语言
m0_531237171 天前
C语言-数组练习进阶
c语言·开发语言·算法