Skip to content

Instantly share code, notes, and snippets.

@bryanburgers
Created November 20, 2023 20:05
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save bryanburgers/677701679ba825ec6d368156297c5434 to your computer and use it in GitHub Desktop.
[package]
name = "wat-playground"
version = "0.1.0"
edition = "2021"
[dependencies]
wasmtime = "15.0.0"
use wasmtime::{Config, Engine, Linker, Module, Store, Val};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Our hand-written file.
let contents = std::fs::read("parse_number.wat")?;
// A whole bunch of wasmtime initialization.
let config = Config::new();
let engine = Engine::new(&config)?;
let module = Module::new(&engine, contents)?;
let linker = Linker::new(&engine);
let mut store = Store::new(&engine, ());
let instance = linker.instantiate(&mut store, &module)?;
// Get the exported "main" function. If we knew exactly what type the main function was,
// `.get_typed_func` would be super valuable. But while playing around, I'm going to allow
// the "main" function to return any values it wants to.
let func = instance
.get_func(&mut store, "main")
.ok_or("no main func")?;
// Initialize a vec to hold all of the return values from "main".
let func_ty = func.ty(&mut store);
let mut results = vec![wasmtime::Val::I32(0); func_ty.results().len()];
// Call main...
func.call(&mut store, &[], &mut results)?;
// And output all of its return values.
for result in results {
match result {
Val::I32(i32) => println!("i32: {i32} (0x{i32:x})"),
Val::I64(i64) => println!("i64: {i64} (0x{i64:x})"),
Val::F32(f32) => println!("f32: {f32}"),
Val::F64(f64) => println!("f64: {f64}"),
Val::V128(v128) => println!("v128: {v128:?}"),
Val::FuncRef(_) => println!("funcref"),
Val::ExternRef(_) => println!("externref"),
}
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment