diff options
| author | Henry Gressmann <mail@henrygressmann.de> | 2024-01-26 18:03:59 +0100 |
|---|---|---|
| committer | Henry Gressmann <mail@henrygressmann.de> | 2024-01-26 18:03:59 +0100 |
| commit | 8adce672578683dcc7ab62e5492e0f5dbc07a0b4 (patch) | |
| tree | eda57b01f206faf5bcfb7ee70c24fd7be8546e66 /examples/wasm-rust.rs | |
| parent | 6fd283b06c4912f5d3408b2072cbc3c4e195a236 (diff) | |
docs: string example
Signed-off-by: Henry Gressmann <mail@henrygressmann.de>
Diffstat (limited to 'examples/wasm-rust.rs')
| -rw-r--r-- | examples/wasm-rust.rs | 35 |
1 files changed, 34 insertions, 1 deletions
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 <rust_example>"); 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()?, _ => {} @@ -51,6 +54,36 @@ fn hello() -> Result<()> { 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::<i32, ()>(&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", "printi32", Extern::typed_func(|_: FuncContext<'_>, x: i32| { println!("{}", x); |
