1 //! Small example of how to serialize compiled wasm module to the disk, 2 //! and then instantiate it from the compilation artifacts. 3 4 // You can execute this example with `cargo run --example serialize` 5 6 use anyhow::Result; 7 use wasmtime::*; 8 9 fn serialize() -> Result<Vec<u8>> { 10 // Configure the initial compilation environment, creating the global 11 // `Store` structure. Note that you can also tweak configuration settings 12 // with a `Config` and an `Engine` if desired. 13 println!("Initializing..."); 14 let engine = Engine::default(); 15 16 // Compile the wasm binary into an in-memory instance of a `Module`. 17 println!("Compiling module..."); 18 let module = Module::from_file(&engine, "examples/hello.wat")?; 19 let serialized = module.serialize()?; 20 21 println!("Serialized."); 22 Ok(serialized) 23 } 24 25 fn deserialize(buffer: &[u8]) -> Result<()> { 26 // Configure the initial compilation environment, creating the global 27 // `Store` structure. Note that you can also tweak configuration settings 28 // with a `Config` and an `Engine` if desired. 29 println!("Initializing..."); 30 let mut store: Store<()> = Store::default(); 31 32 // Compile the wasm binary into an in-memory instance of a `Module`. Note 33 // that this is `unsafe` because it is our responsibility for guaranteeing 34 // that these bytes are valid precompiled module bytes. We know that from 35 // the structure of this example program. 36 println!("Deserialize module..."); 37 let module = unsafe { Module::deserialize(store.engine(), buffer)? }; 38 39 // Here we handle the imports of the module, which in this case is our 40 // `HelloCallback` type and its associated implementation of `Callback. 41 println!("Creating callback..."); 42 let hello_func = Func::wrap(&mut store, || { 43 println!("Calling back..."); 44 println!("> Hello World!"); 45 }); 46 47 // Once we've got that all set up we can then move to the instantiation 48 // phase, pairing together a compiled module as well as a set of imports. 49 // Note that this is where the wasm `start` function, if any, would run. 50 println!("Instantiating module..."); 51 let imports = [hello_func.into()]; 52 let instance = Instance::new(&mut store, &module, &imports)?; 53 54 // Next we poke around a bit to extract the `run` function from the module. 55 println!("Extracting export..."); 56 let run = instance.get_typed_func::<(), (), _>(&mut store, "run")?; 57 58 // And last but not least we can call it! 59 println!("Calling export..."); 60 run.call(&mut store, ())?; 61 62 println!("Done."); 63 Ok(()) 64 } 65 66 fn main() -> Result<()> { 67 let file = serialize()?; 68 deserialize(&file) 69 } 70