Files
wasmtime/crates/api/examples/gcd.rs
Alex Crichton b9dc38f4e1 Remove need for HostRef<Engine> (#762)
This commit removes the need to use `HostRef<Engine>` in the Rust API.
Usage is retained in the C API in one location, but otherwise `Engine`
can always be used directly.

This is the first step of progress on #708 for the `Engine` type.
Changes here include:

* `Engine` is now `Clone`, and is documented as being cheap. It's not
  intended that cloning an engine creates a deep copy.
* `Engine` is now both `Send` and `Sync`, and asserted to be so.
* Usage of `Engine` in APIs no longer requires or uses `HostRef`.
2020-01-06 15:17:03 -06:00

70 lines
1.5 KiB
Rust

//! Example of instantiating of the WebAssembly module and
//! invoking its exported function.
use anyhow::{format_err, Result};
use wasmtime::*;
const WAT: &str = r#"
(module
(func $gcd (param i32 i32) (result i32)
(local i32)
block ;; label = @1
block ;; label = @2
local.get 0
br_if 0 (;@2;)
local.get 1
local.set 2
br 1 (;@1;)
end
loop ;; label = @2
local.get 1
local.get 0
local.tee 2
i32.rem_u
local.set 0
local.get 2
local.set 1
local.get 0
br_if 0 (;@2;)
end
end
local.get 2
)
(export "gcd" (func $gcd))
)
"#;
fn main() -> Result<()> {
let wasm = wat::parse_str(WAT)?;
// Instantiate engine and store.
let engine = Engine::default();
let store = HostRef::new(Store::new(&engine));
// Load a module.
let module = HostRef::new(Module::new(&store, &wasm)?);
// Find index of the `gcd` export.
let gcd_index = module
.borrow()
.exports()
.iter()
.enumerate()
.find(|(_, export)| export.name().to_string() == "gcd")
.unwrap()
.0;
// Instantiate the module.
let instance = Instance::new(&store, &module, &[])?;
// Invoke `gcd` export
let gcd = instance.exports()[gcd_index].func().expect("gcd");
let result = gcd
.borrow()
.call(&[Val::from(6i32), Val::from(27i32)])
.map_err(|e| format_err!("call error: {:?}", e))?;
println!("{:?}", result);
Ok(())
}