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