wasmedge_sys/frame.rs
1//! Defines WasmEdge CallingFrame.
2
3use crate::{
4 ffi,
5 instance::{memory::InnerMemory, InnerRef},
6 Memory,
7};
8
9/// Represents a calling frame on top of stack.
10#[derive(Debug)]
11pub struct CallingFrame {
12 pub(crate) inner: InnerCallingFrame,
13}
14
15impl CallingFrame {
16 /// Creates a CallingFrame instance.
17 pub(crate) fn create(ctx: *const ffi::WasmEdge_CallingFrameContext) -> Self {
18 Self {
19 inner: InnerCallingFrame(ctx),
20 }
21 }
22
23 /// Returns an immutable smart pointer borrowing the [memory instance](crate::Memory) by the given index from the module instance of the current
24 /// calling frame. If the memory instance is not found, returns `None`.
25 ///
26 /// By default, a WASM module has only one memory instance after instantiation. Therefore, users can pass in `0` as
27 /// the index to get the memory instance in host function body. When the [MultiMemories](crate::Config::multi_memories)
28 /// config option is enabled, there would be more than one memory instances in the wasm module. Users can retrieve
29 /// the target memory instance by specifying the index of the memory instance in the wasm module instance.
30 ///
31 /// # Arguments
32 ///
33 /// * idx - The index of the memory instance.
34 pub fn memory_ref(&self, idx: u32) -> Option<InnerRef<Memory, &Self>> {
35 unsafe {
36 let ctx = ffi::WasmEdge_CallingFrameGetMemoryInstance(self.inner.0, idx);
37
38 if ctx.is_null() {
39 None
40 } else {
41 let mem = Memory {
42 inner: InnerMemory(ctx),
43 };
44 Some(InnerRef::create_from_ref(
45 std::mem::ManuallyDrop::new(mem),
46 self,
47 ))
48 }
49 }
50 }
51
52 /// Returns an mutable smart pointer borrowing the [memory instance](crate::Memory) by the given index from the module instance of the current
53 /// calling frame. If the memory instance is not found, returns `None`.
54 ///
55 /// By default, a WASM module has only one memory instance after instantiation. Therefore, users can pass in `0` as
56 /// the index to get the memory instance in host function body. When the [MultiMemories](crate::Config::multi_memories)
57 /// config option is enabled, there would be more than one memory instances in the wasm module. Users can retrieve
58 /// the target memory instance by specifying the index of the memory instance in the wasm module instance.
59 ///
60 /// # Arguments
61 ///
62 /// * idx - The index of the memory instance.
63 pub fn memory_mut(&mut self, idx: u32) -> Option<InnerRef<Memory, &mut Self>> {
64 unsafe {
65 let ctx = ffi::WasmEdge_CallingFrameGetMemoryInstance(self.inner.0, idx);
66
67 if ctx.is_null() {
68 None
69 } else {
70 let mem = Memory {
71 inner: InnerMemory(ctx),
72 };
73 Some(InnerRef::create_from_mut(
74 std::mem::ManuallyDrop::new(mem),
75 self,
76 ))
77 }
78 }
79 }
80}
81
82#[derive(Debug)]
83pub(crate) struct InnerCallingFrame(pub(crate) *const ffi::WasmEdge_CallingFrameContext);
84unsafe impl Send for InnerCallingFrame {}
85unsafe impl Sync for InnerCallingFrame {}