Skip to content

Instantly share code, notes, and snippets.

@autodidaddict
Created December 14, 2019 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save autodidaddict/77c7e18e6bdab8cb912fe1b1b8bfe086 to your computer and use it in GitHub Desktop.
Save autodidaddict/77c7e18e6bdab8cb912fe1b1b8bfe086 to your computer and use it in GitHub Desktop.
wasmtime chicken and egg
use wasmtime::{Callable, Engine, Extern, FuncType, HostRef, Module, Store, Trap, Val, ValType};
// The goal of this code is that I need a function invoked by the guest wasm module on the
// host to be able to access the memory of that instance, and to be able to call additional
// functions on that instance in response.
//
// When I use wasmer, the call signature includes a Ctx, which allows me to manipulate the instance
// memory and call functions.
struct GuestCallable {}
impl Callable for GuestCallable {
fn call(
&self,
params: &[Val],
results: &mut [Val],
) -> ::std::result::Result<(), HostRef<Trap>> {
// How does this thing access the memory of the instance that invoked it??
Ok(())
}
}
fn main() -> {
let engine = HostRef::new(Engine::default());
let store = HostRef::new(Store::new(&engine));
let module = HostRef::new(Module::new(&store, buf).expect("wasm module"));
let ft = FuncType::new(
Box::new([ValType::I32, ValType::I32, ValType::I32, ValType::I32]),
Box::new([ValType::I32]),
);
let callable = GuestCallable {};
let f = wasmtime::Func::new(&store, ft, Rc::new(callable));
let e = Extern::Func(HostRef::new(f));
let instance = wasmtime::Instance::new(&store, &module, &[e]).expect("wasm instance");
// At this point I've got a callable that's moved out of scope, so I can't
// go back and give it a reference to the instance or the instance handle.
}
@autodidaddict
Copy link
Author

The requirements for Func::new() are that something implement Callable... would an Arc also implement Callable? Would that even work given that wasmtime's Instance type is !Send and !Sync ?

@autodidaddict
Copy link
Author

Unrelated to the chicken and the egg - this extern has no name - how does the guest module get the right import namespace and function name for dispatch?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment