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,并且打开调试控制台,可以看到运行结果。

相关推荐
ssshooter6 小时前
Tauri 项目实践:客户端与 Web 端的授权登录实现方案
前端·后端·rust
AI智动派9 小时前
《深入 Rust Async/Await:如何实现一个带超时保护与安全沙箱的 LLM Agent 循环》
rust
范特西林2 天前
一次 to_bits() 引发的 Rust 与 C++ 底层思考
rust
冬奇Lab3 天前
一天一个开源项目(第42篇):OpenFang - 用 Rust 构建的 Agent 操作系统,16 层安全与 7 个自主 Hands
人工智能·rust·开源
量子位3 天前
Transformer论文作者重造龙虾,Rust搓出钢铁版,告别OpenClaw裸奔漏洞
rust·openai·ai编程
哈里谢顿3 天前
Rust 语言入门博客
rust
DongLi015 天前
rustlings 学习笔记 -- exercises/06_move_semantics
rust
ssshooter5 天前
Tauri 踩坑 appLink 修改后闪退
前端·ios·rust
布列瑟农的星空5 天前
前端都能看懂的rust入门教程(二)——函数和闭包
前端·后端·rust
蚂蚁背大象6 天前
Rust 所有权系统是为了解决什么问题
后端·rust