zwasm-sdk provides safe, idiomatic Rust bindings to the zwasm WebAssembly runtime.
A recent stable Rust compiler is recommended. (Rust 2021 edition)
- Requires Zig 0.16.0 in your PATH (used to build the zwasm C library)
- Supported platforms: Linux (x86_64, aarch64), macOS (x86_64, aarch64)
The zwasm C library is built from the vendored submodule and linked statically, so no shared library has to be installed on the machine that runs your binary.
| zwasm-sdk | zwasm-sys | zwasm C API |
|---|---|---|
| 0.2.x | 0.2.x | 2.5.x |
| 0.1.x | 0.1.x | 1.11.x |
zwasm 2.0 replaced the custom C API with the standard wasm-c-api, so 0.2 is a full rewrite with no path from 0.1. See CHANGELOG.md.
Add this to your Cargo.toml:
[dependencies]
zwasm-sdk = "0.2"use zwasm_sdk::engine::Engine;
use zwasm_sdk::instance::Instance;
use zwasm_sdk::module::Module;
use zwasm_sdk::store::Store;
use zwasm_sdk::val::Val;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let wasm = std::fs::read("your_module.wasm")?;
let engine = Engine::new()?;
let store = Store::new(&engine)?;
let module = Module::new(&store, &wasm)?;
let instance = Instance::new(&store, &module, &[])?;
let add = instance.get_func_by_name(&module, "add")?;
let results = add.call(&[Val::I32(10), Val::I32(32)])?;
println!("results = {results:?}");
Ok(())
}Engine, Store, Module, Instance and Func mirror the wasm-c-api object model. Each one frees its C counterpart on drop.
Build a WasiConfig and install it on the store before instantiating. The store takes ownership of the config, so it is passed by value.
use zwasm_sdk::engine::Engine;
use zwasm_sdk::store::Store;
use zwasm_sdk::wasi::WasiConfig;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let engine = Engine::new()?;
let mut store = Store::new(&engine)?;
let mut wasi = WasiConfig::new()?;
wasi.set_args(&["prog", "--flag"])?;
wasi.set_envs(&[("KEY", "VALUE")])?;
wasi.preopen_dir("/host/dir", "/")?;
wasi.inherit_stdio();
store.set_wasi(wasi);
Ok(())
}Imports of wasi_snapshot_preview1.* then resolve against that host. WASI 0.1 is supported; the Component Model and WASI 0.2 surfaces of zwasm are not wrapped yet.
All FFI unsafety is encapsulated, except for host functions: Func::new_host still takes a raw wasm_functype_t and a C callback. A safe builder for function types is not implemented yet.
Engine is Send + Sync. Store and everything derived from it are single-threaded.
For low-level access, see zwasm-sys.
MIT License. See LICENSE for details.
Contributions, bug reports, and feature requests are welcome! See CONTRIBUTING.md for details.