diff --git a/sdk/rust/dim_sdk/src/lib.rs b/sdk/rust/dim_sdk/src/lib.rs index 8b4fbf5..5c9d5e5 100644 --- a/sdk/rust/dim_sdk/src/lib.rs +++ b/sdk/rust/dim_sdk/src/lib.rs @@ -1,5 +1,4 @@ - #[macro_use] mod magic; mod c_buffer; @@ -11,7 +10,7 @@ pub use plugin_info::*; pub use anyhow::Result; pub use context::*; -pub trait DimPlugin { +pub trait DimPlugin: Clone { fn init(&mut self, ctx: Context); fn pre_reload(&mut self); fn post_reload(&mut self); diff --git a/sdk/rust/dim_sdk/src/magic.rs b/sdk/rust/dim_sdk/src/magic.rs index 8256fc8..aa557b0 100644 --- a/sdk/rust/dim_sdk/src/magic.rs +++ b/sdk/rust/dim_sdk/src/magic.rs @@ -7,7 +7,7 @@ macro_rules! plugin_info { static ref PLUGIN_INFO: $crate::PluginInfo = $crate::PluginInfo::new($name, $version, $license); ); - static mut PLUG: *mut $typ = std::ptr::null_mut() as *mut $typ; + static mut PLUG: Option<$typ> = None as Option<$typ>; #[no_mangle] unsafe extern "C" fn plug_get_info() -> *const std::ffi::c_void { @@ -16,39 +16,59 @@ macro_rules! plugin_info { #[no_mangle] unsafe extern "C" fn plug_init(ctx: *const $crate::ContextRaw) { - PLUG = std::alloc::alloc(std::alloc::Layout::new::<$typ>()) as *mut $typ; - *PLUG = Plug::new(); + //PLUG = std::alloc::alloc(std::alloc::Layout::new::<$typ>()) as *mut $typ; + PLUG = Some(Plug::new()); let ctx = $crate::Context::new(ctx); - (&mut *PLUG).init(ctx); + if let Some(p) = &mut PLUG { + p.init(ctx) + } else { + unreachable!(); + } } #[no_mangle] unsafe extern "C" fn plug_pre_reload() -> *mut $typ { //TODO: Untested - (&mut *PLUG).pre_reload(); - return PLUG; + if let Some(p) = &mut PLUG { + p.pre_reload(); + return p as *mut $typ; + } + unreachable!(); } #[no_mangle] unsafe extern "C" fn plug_post_reload(state: *mut $typ) { - //TODO: Untested - PLUG = state; - (&mut *PLUG).post_reload(); + PLUG = Some((*state).clone()); + + if let Some(p) = &mut PLUG { + p.post_reload(); + } else { + unreachable!(); + } + //TODO: Untested } #[no_mangle] unsafe extern "C" fn plug_poll(buf: *mut i8, len: std::ffi::c_uint) { let mut buf = $crate::CBuffer::from_raw_parts_mut(buf, len as usize); - if let Err(_e) = (&mut *PLUG).poll(&mut buf) { - // TODO: Handle error maybe? + if let Some(p) = &mut PLUG { + if let Err(_e) = p.poll(&mut buf) { + // TODO: Handle error maybe? + } + } else { + unreachable!(); } } #[no_mangle] unsafe extern "C" fn plug_free() { - std::alloc::dealloc(PLUG as *mut u8, std::alloc::Layout::new::<$typ>()); - (&mut *PLUG).free(); + if let Some(p) = &mut PLUG { + // std::alloc::dealloc(PLUG as *mut u8, std::alloc::Layout::new::<$typ>()); + p.free(); + } else { + unreachable!(); + } } };