From 8adce672578683dcc7ab62e5492e0f5dbc07a0b4 Mon Sep 17 00:00:00 2001 From: Henry Gressmann Date: Fri, 26 Jan 2024 18:03:59 +0100 Subject: docs: string example Signed-off-by: Henry Gressmann --- examples/wasm-rust.rs | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) (limited to 'examples/wasm-rust.rs') diff --git a/examples/wasm-rust.rs b/examples/wasm-rust.rs index 3b26863..6580bd5 100644 --- a/examples/wasm-rust.rs +++ b/examples/wasm-rust.rs @@ -7,12 +7,15 @@ fn main() -> Result<()> { println!("Usage: cargo run --example wasm-rust "); println!("Available examples:"); println!(" hello"); - println!(" tinywasm"); + println!(" printi32"); + println!(" fibonacci - calculate fibonacci(30)"); + println!(" tinywasm - run printi32 inside of tinywasm inside of itself"); return Ok(()); } match args[1].as_str() { "hello" => hello()?, + "printi32" => printi32()?, "fibonacci" => fibonacci()?, "tinywasm" => tinywasm()?, _ => {} @@ -48,6 +51,36 @@ fn hello() -> Result<()> { let module = Module::parse_bytes(&HELLO_WASM)?; let mut store = Store::default(); + let mut imports = Imports::new(); + imports.define( + "env", + "print_utf8", + Extern::typed_func(|mut ctx: FuncContext<'_>, args: (i32, i32)| { + let mem = ctx.memory("memory")?; + let ptr = args.1 as usize; + let len = args.0 as usize; + let string = mem.load_string(ptr, len)?; + println!("{}", string); + Ok(()) + }), + )?; + + let instance = module.instantiate(&mut store, Some(imports))?; + let arg_ptr = instance.exported_func::<(), i32>(&mut store, "arg_ptr")?.call(&mut store, ())?; + let arg = b"world"; + + instance.exported_memory(&mut store, "memory")?.store(arg_ptr as usize, arg.len(), arg)?; + let hello = instance.exported_func::(&mut store, "hello")?; + hello.call(&mut store, arg.len() as i32)?; + + Ok(()) +} + +fn printi32() -> Result<()> { + const HELLO_WASM: &[u8] = include_bytes!("./rust/out/print.wasm"); + let module = Module::parse_bytes(&HELLO_WASM)?; + let mut store = Store::default(); + let mut imports = Imports::new(); imports.define( "env", -- cgit v1.3.1