-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
wasmtime: Add
externref
Rust example
- Loading branch information
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
//! Small example of how to use `externref`s. | ||
|
||
// You can execute this example with `cargo run --example externref` | ||
|
||
use anyhow::Result; | ||
use wasmtime::*; | ||
|
||
fn main() -> Result<()> { | ||
println!("Initializing..."); | ||
let mut config = Config::new(); | ||
config.wasm_reference_types(true); | ||
let engine = Engine::new(&config); | ||
let store = Store::new(&engine); | ||
|
||
println!("Compiling module..."); | ||
let module = Module::from_file(&engine, "examples/externref.wat")?; | ||
|
||
println!("Instantiating module..."); | ||
let imports = []; | ||
let instance = Instance::new(&store, &module, &imports)?; | ||
|
||
println!("Creating new `externref`..."); | ||
let externref = ExternRef::new("Hello, World!"); | ||
assert!(externref.data().is::<&'static str>()); | ||
assert_eq!( | ||
*externref.data().downcast_ref::<&'static str>().unwrap(), | ||
"Hello, World!" | ||
); | ||
|
||
println!("Touching `externref` table..."); | ||
let table = instance.get_table("table").unwrap(); | ||
table.set(3, Some(externref.clone()).into())?; | ||
let elem = table.get(3).unwrap().unwrap_externref().unwrap(); | ||
assert!(elem.ptr_eq(&externref)); | ||
|
||
println!("Touching `externref` global..."); | ||
let global = instance.get_global("global").unwrap(); | ||
global.set(Some(externref.clone()).into())?; | ||
let global_val = global.get().unwrap_externref().unwrap(); | ||
assert!(global_val.ptr_eq(&externref)); | ||
|
||
println!("Calling `externref` func..."); | ||
let func = instance.get_func("func").unwrap(); | ||
let func = func.get1::<Option<ExternRef>, Option<ExternRef>>()?; | ||
let ret = func(Some(externref.clone()))?; | ||
assert!(ret.is_some()); | ||
assert!(ret.unwrap().ptr_eq(&externref)); | ||
|
||
println!("Done."); | ||
Ok(()) | ||
} |