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