WebAssembly 与 Rust 编程系列05 Rust编写wasm模块
Rust 开发环境安装
下载 rustup-init.exe
点击安装
完成之后会在我们的用户Home目录添加两个文件夹
- .cargo/bin: cargo 及 rust 相应的命令行工具
- .rustup: rust的配置目录
其中 cargo 是 rust的包管理工具,类似npm之于node,maven之于java,composer之于PHP
检查安装
C:\Users\admin>rustc --version
rustc 1.44.1 (c7087fe00 2020-06-17)
C:\Users\admin>rustup --version
rustup 1.21.1 (7832b2ebe 2019-12-20)
安装 WEBASSEMBLY 目标
我们需要把rust代码编译成wasm目标模块,必须安装 rust WebAssembly 对应的target
我们可以通过 rustup 的target命令, 了解可用的target 以及是否安装
C:\Users\admin>rustup target --help
rustup-target
Modify a toolchain's supported targets
USAGE:
rustup target <SUBCOMMAND>
FLAGS:
-h, --help Prints help information
SUBCOMMANDS:
list List installed and available targets
add Add a target to a Rust toolchain
remove Remove a target from a Rust toolchain
help Prints this message or the help of the given subcommand(s)
显示列表: rustup target list
C:\Users\admin>rustup target list
aarch64-apple-ios
arm-linux-androideabi
arm-unknown-linux-gnueabi
arm-unknown-linux-gnueabihf
arm-unknown-linux-musleabi
...
...
thumbv7neon-unknown-linux-gnueabihf
thumbv8m.base-none-eabi
thumbv8m.main-none-eabi
thumbv8m.main-none-eabihf
wasm32-unknown-emscripten
wasm32-unknown-unknown
wasm32-wasi
x86_64-apple-darwin
x86_64-apple-ios
x86_64-fortanix-unknown-sgx
x86_64-fuchsia
x86_64-linux-android
x86_64-pc-windows-gnu
x86_64-pc-windows-msvc (installed)
x86_64-rumprun-netbsd
我们需要安装的是 wasm32-unknown-unknown
rustup target add wasm32-unknown-unknown
rust WebAssembly Hello Project
创建新的空工程
cargo new --lib hello-wasm
在 Cargo.toml 中包含了工程的基本信息
[package]
name = "hello-wasm"
version = "0.1.0"
authors = ["austindev <austinxishou@yahoo.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
在 src/lib.rs 只有最基本的测试示例:
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
当然可以直接运行 cargo test
执行测试,当然这里我们并不需要它,可以直接删除
定义一个简单函数并导出:
# [no_mangle]
pub extern "C" fn add_one(x: i32)-> i32 {
x + 1
}
编译成wasm
> cargo build --release --target wasm32-unknown-unknown
Finished release [optimized] target(s) in 0.02s
js 引用demo
fetch('hello_wasm.wasm')
.then(res =>
res.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, {})
).then(results => {
console.log(`wasm `, results.instance.exports)
console.log('wasm call result:' + results.instance.exports.add_one(3));
});
控制台输出: