Instance now pulls state from the ImportObject

This commit is contained in:
Lachlan Sneff
2019-03-28 11:56:31 -07:00
parent e3a6b7c9d8
commit 7b0992e44f
4 changed files with 19 additions and 6 deletions

View File

@ -3,8 +3,8 @@ use hashbrown::{hash_map::Entry, HashMap};
use std::collections::VecDeque; use std::collections::VecDeque;
use std::{ use std::{
cell::{Ref, RefCell}, cell::{Ref, RefCell},
rc::Rc,
ffi::c_void, ffi::c_void,
rc::Rc,
}; };
pub trait LikeNamespace { pub trait LikeNamespace {
@ -58,7 +58,7 @@ impl ImportObject {
} }
} }
pub fn new_with_data<F>(state_creator: F) -> Self pub fn new_with_data<F>(state_creator: F) -> Self
where where
F: Fn() -> (*mut c_void, fn(*mut c_void)) + 'static, 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. /// Register anything that implements `LikeNamespace` as a namespace.
/// ///
/// # Usage: /// # Usage:

View File

@ -63,7 +63,16 @@ impl Instance {
// Initialize the vm::Ctx in-place after the backing // Initialize the vm::Ctx in-place after the backing
// has been boxed. // has been boxed.
unsafe { 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 { let instance = Instance {

View File

@ -37,7 +37,7 @@ macro_rules! func {
/// "foo" => func!(foo), /// "foo" => func!(foo),
/// }, /// },
/// }; /// };
/// ///
/// let imports_with_state = imports! { /// let imports_with_state = imports! {
/// || (0 as _, |_a| {}), /// || (0 as _, |_a| {}),
/// "env" => { /// "env" => {

View File

@ -25,7 +25,7 @@ pub struct Ctx {
module: *const ModuleInner, module: *const ModuleInner,
pub data: *mut c_void, pub data: *mut c_void,
pub data_finalizer: Option<extern "C" fn(data: *mut c_void)>, pub data_finalizer: Option<fn(data: *mut c_void)>,
} }
/// The internal context of the currently running WebAssembly instance. /// The internal context of the currently running WebAssembly instance.
@ -100,7 +100,7 @@ impl Ctx {
import_backing: &mut ImportBacking, import_backing: &mut ImportBacking,
module: &ModuleInner, module: &ModuleInner,
data: *mut c_void, data: *mut c_void,
data_finalizer: extern "C" fn(*mut c_void), data_finalizer: fn(*mut c_void),
) -> Self { ) -> Self {
Self { Self {
internal: InternalCtx { internal: InternalCtx {