1use crate::{
2 WasmStoreRef,
3 wasm_extern_t,
4 wasm_extern_vec_t,
5 wasm_module_t,
6 wasm_store_t,
7 wasm_trap_t,
8};
9use alloc::boxed::Box;
10use wasmi::Instance;
11
12#[derive(Clone)]
16pub struct wasm_instance_t {
17 store: WasmStoreRef,
18 inner: Instance,
19}
20
21wasmi_c_api_macros::declare_ref!(wasm_instance_t);
22
23impl wasm_instance_t {
24 pub(crate) fn new(store: WasmStoreRef, instance: Instance) -> wasm_instance_t {
26 wasm_instance_t {
27 store,
28 inner: instance,
29 }
30 }
31}
32
33#[cfg_attr(not(feature = "prefix-symbols"), unsafe(no_mangle))]
47#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
48pub unsafe extern "C" fn wasm_instance_new(
49 store: &mut wasm_store_t,
50 wasm_module: &wasm_module_t,
51 imports: *const wasm_extern_vec_t,
52 result: Option<&mut *mut wasm_trap_t>,
53) -> Option<Box<wasm_instance_t>> {
54 unsafe {
55 let imports = (*imports)
56 .as_slice()
57 .iter()
58 .filter_map(|import| import.as_ref().map(|i| i.which))
59 .collect::<Box<[_]>>();
60 match Instance::new(store.inner.context_mut(), &wasm_module.inner, &imports) {
61 Ok(instance) => Some(Box::new(wasm_instance_t::new(
62 store.inner.clone(),
63 instance,
64 ))),
65 Err(e) => {
66 if let Some(ptr) = result {
67 *ptr = Box::into_raw(Box::new(wasm_trap_t::new(e)));
68 }
69 None
70 }
71 }
72 }
73}
74
75#[cfg_attr(not(feature = "prefix-symbols"), unsafe(no_mangle))]
86#[cfg_attr(feature = "prefix-symbols", wasmi_c_api_macros::prefix_symbol)]
87pub unsafe extern "C" fn wasm_instance_exports(
88 instance: &mut wasm_instance_t,
89 out: &mut wasm_extern_vec_t,
90) {
91 unsafe {
92 let store = instance.store.clone();
93 out.set_buffer(
94 instance
95 .inner
96 .exports(&mut instance.store.context_mut())
97 .map(|e| {
98 Some(Box::new(wasm_extern_t {
99 which: e.into_extern(),
100 store: store.clone(),
101 }))
102 })
103 .collect(),
104 );
105 }
106}