diff --git a/lib/runtime-core/src/import.rs b/lib/runtime-core/src/import.rs index 32b089462..14465deed 100644 --- a/lib/runtime-core/src/import.rs +++ b/lib/runtime-core/src/import.rs @@ -3,8 +3,8 @@ use hashbrown::{hash_map::Entry, HashMap}; use std::collections::VecDeque; use std::{ cell::{Ref, RefCell}, - rc::Rc, ffi::c_void, + rc::Rc, }; pub trait LikeNamespace { @@ -58,7 +58,7 @@ impl ImportObject { } } - pub fn new_with_data(state_creator: F) -> Self + pub fn new_with_data(state_creator: F) -> Self where F: Fn() -> (*mut c_void, fn(*mut c_void)) + 'static, { @@ -68,6 +68,10 @@ impl ImportObject { } } + pub(crate) fn call_state_creator(&self) -> Option<(*mut c_void, fn(*mut c_void))> { + self.state_creator.as_ref().map(|state_gen| state_gen()) + } + /// Register anything that implements `LikeNamespace` as a namespace. /// /// # Usage: diff --git a/lib/runtime-core/src/instance.rs b/lib/runtime-core/src/instance.rs index ba1dcba37..956b95d7b 100644 --- a/lib/runtime-core/src/instance.rs +++ b/lib/runtime-core/src/instance.rs @@ -63,7 +63,16 @@ impl Instance { // Initialize the vm::Ctx in-place after the backing // has been boxed. unsafe { - *inner.vmctx = vm::Ctx::new(&mut inner.backing, &mut inner.import_backing, &module) + *inner.vmctx = match imports.call_state_creator() { + Some((data, dtor)) => vm::Ctx::new_with_data( + &mut inner.backing, + &mut inner.import_backing, + &module, + data, + dtor, + ), + None => vm::Ctx::new(&mut inner.backing, &mut inner.import_backing, &module), + }; }; let instance = Instance { diff --git a/lib/runtime-core/src/macros.rs b/lib/runtime-core/src/macros.rs index 6c608fc92..0fb1c3fc9 100644 --- a/lib/runtime-core/src/macros.rs +++ b/lib/runtime-core/src/macros.rs @@ -37,7 +37,7 @@ macro_rules! func { /// "foo" => func!(foo), /// }, /// }; -/// +/// /// let imports_with_state = imports! { /// || (0 as _, |_a| {}), /// "env" => { diff --git a/lib/runtime-core/src/vm.rs b/lib/runtime-core/src/vm.rs index 8b970587e..90afbc408 100644 --- a/lib/runtime-core/src/vm.rs +++ b/lib/runtime-core/src/vm.rs @@ -25,7 +25,7 @@ pub struct Ctx { module: *const ModuleInner, pub data: *mut c_void, - pub data_finalizer: Option, + pub data_finalizer: Option, } /// The internal context of the currently running WebAssembly instance. @@ -100,7 +100,7 @@ impl Ctx { import_backing: &mut ImportBacking, module: &ModuleInner, data: *mut c_void, - data_finalizer: extern "C" fn(*mut c_void), + data_finalizer: fn(*mut c_void), ) -> Self { Self { internal: InternalCtx {