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

相关推荐
长河36 分钟前
Java开发者LLM实战——LangChain4j最新版教学知识库实战
java·开发语言
Cyan_RA91 小时前
SpringMVC @RequestMapping的使用演示和细节 详解
java·开发语言·后端·spring·mvc·ssm·springmvc
再见晴天*_*4 小时前
SpringBoot 中单独一个类中运行main方法报错:找不到或无法加载主类
java·开发语言·intellij idea
lqjun08275 小时前
Qt程序单独运行报错问题
开发语言·qt
ftpeak5 小时前
从零开始使用 axum-server 构建 HTTP/HTTPS 服务
网络·http·https·rust·web·web app
咸甜适中6 小时前
rust语言 (1.88) 学习笔记:客户端和服务器端同在一个项目中
笔记·学习·rust
hdsoft_huge7 小时前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
风中的微尘7 小时前
39.网络流入门
开发语言·网络·c++·算法
未来之窗软件服务8 小时前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
小冯记录编程8 小时前
C++指针陷阱:高效背后的致命危险
开发语言·c++·visual studio