diff options
| author | Henry Gressmann <mail@henrygressmann.de> | 2024-01-26 12:03:59 +0100 |
|---|---|---|
| committer | Henry Gressmann <mail@henrygressmann.de> | 2024-01-26 12:03:59 +0100 |
| commit | f3d890a36d6299dbd70377ce57b0bd9d61de5c1b (patch) | |
| tree | 36b51022af641c0f464fd0c5d4456b722e5f735b /examples/wasm-rust.rs | |
| parent | 461126ce309f99e4ad2a6ddcbc175ea01c5e8fee (diff) | |
docs: working selfhosted example
Signed-off-by: Henry Gressmann <mail@henrygressmann.de>
Diffstat (limited to 'examples/wasm-rust.rs')
| -rw-r--r-- | examples/wasm-rust.rs | 54 |
1 files changed, 39 insertions, 15 deletions
diff --git a/examples/wasm-rust.rs b/examples/wasm-rust.rs index 21d3eb8..3b8877e 100644 --- a/examples/wasm-rust.rs +++ b/examples/wasm-rust.rs @@ -7,35 +7,59 @@ fn main() -> Result<()> { println!("Usage: cargo run --example wasm-rust <rust_example>"); println!("Available examples:"); println!(" hello"); + println!(" tinywasm"); return Ok(()); } match args[1].as_str() { "hello" => hello()?, + "tinywasm" => tinywasm()?, _ => {} } Ok(()) } +fn tinywasm() -> Result<()> { + const TINYWASM: &[u8] = include_bytes!("./rust/out/tinywasm.wasm"); + let module = Module::parse_bytes(&TINYWASM)?; + let mut store = Store::default(); + + let mut imports = Imports::new(); + imports.define( + "env", + "printi32", + Extern::typed_func(|_: FuncContext<'_>, x: i32| { + println!("{}", x); + Ok(()) + }), + )?; + let instance = module.instantiate(&mut store, Some(imports))?; + + let hello = instance.typed_func::<(), ()>(&mut store, "hello")?; + hello.call(&mut store, ())?; + + Ok(()) +} + fn hello() -> Result<()> { - // const HELLO_WASM: &[u8] = include_bytes!("./rust/out/hello.wasm"); - // let module = Module::parse_bytes(&HELLO_WASM)?; - // let mut store = Store::default(); + const HELLO_WASM: &[u8] = include_bytes!("./rust/out/hello.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); - // Ok(()) - // }), - // )?; + let mut imports = Imports::new(); + imports.define( + "env", + "printi32", + Extern::typed_func(|_: FuncContext<'_>, x: i32| { + println!("{}", x); + Ok(()) + }), + )?; - // let instance = module.instantiate(&mut store, Some(imports))?; - // let add_and_print = instance.typed_func::<(i32, i32), ()>(&mut store, "add_and_print")?; - // add_and_print.call(&mut store, (1, 2))?; + let instance = module.instantiate(&mut store, Some(imports))?; + let add_and_print = instance.typed_func::<(i32, i32), ()>(&mut store, "add_and_print")?; + add_and_print.call(&mut store, (1, 2))?; Ok(()) } |
