1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
//! Small example of how to use `externref`s.
// You can execute this example with `cargo run --example externref`
use wasmtime::*;
fn main() -> Result<()> {
println!("Initializing...");
let mut config = Config::new();
config.wasm_reference_types(true);
let engine = Engine::new(&config)?;
let mut store = Store::new(&engine, ());
println!("Compiling module...");
let module = Module::from_file(&engine, "examples/externref.wat")?;
println!("Instantiating module...");
let instance = Instance::new(&mut store, &module, &[])?;
println!("Creating new `externref`...");
let externref = ExternRef::new(&mut store, "Hello, World!")?;
assert!(externref.data(&store)?.is::<&'static str>());
assert_eq!(
*externref
.data(&store)?
.downcast_ref::<&'static str>()
.unwrap(),
"Hello, World!"
);
println!("Touching `externref` table...");
let table = instance.get_table(&mut store, "table").unwrap();
table.set(&mut store, 3, Some(externref).into())?;
let elem = table
.get(&mut store, 3)
.unwrap() // assert in bounds
.unwrap_extern() // assert it's an externref table
.copied()
.unwrap(); // assert the externref isn't null
assert!(Rooted::ref_eq(&store, &elem, &externref)?);
println!("Touching `externref` global...");
let global = instance.get_global(&mut store, "global").unwrap();
global.set(&mut store, Some(externref).into())?;
let global_val = global.get(&mut store).unwrap_externref().copied().unwrap();
assert!(Rooted::ref_eq(&store, &global_val, &externref)?);
println!("Calling `externref` func...");
let func = instance.get_typed_func::<Option<Rooted<ExternRef>>, Option<Rooted<ExternRef>>>(
&mut store, "func",
)?;
let ret = func.call(&mut store, Some(externref))?;
assert!(ret.is_some());
assert!(Rooted::ref_eq(&store, &ret.unwrap(), &externref)?);
println!("GCing within the store...");
store.gc();
println!("Done.");
Ok(())
}
|