diff --git a/crates/backend/src/codegen/fn.rs b/crates/backend/src/codegen/fn.rs index 35e2df94..0c7e48a4 100644 --- a/crates/backend/src/codegen/fn.rs +++ b/crates/backend/src/codegen/fn.rs @@ -147,8 +147,8 @@ impl NapiFn { if let Some(p) = path.path.segments.first() { if p.ident == *self.parent.as_ref().unwrap() { args.push( - quote! { napi::bindgen_prelude::Reference::from_value_ptr(this_ptr as *mut std::ffi::c_void, env)? }, - ); + quote! { napi::bindgen_prelude::Reference::from_value_ptr(this_ptr as *mut std::ffi::c_void, env)? }, + ); skipped_arg_count += 1; continue; } diff --git a/crates/napi/src/bindgen_runtime/js_values/value_ref.rs b/crates/napi/src/bindgen_runtime/js_values/value_ref.rs index 90acf295..9f61d76f 100644 --- a/crates/napi/src/bindgen_runtime/js_values/value_ref.rs +++ b/crates/napi/src/bindgen_runtime/js_values/value_ref.rs @@ -180,6 +180,15 @@ impl Clone for WeakReference { impl ToNapiValue for WeakReference { unsafe fn to_napi_value(env: crate::sys::napi_env, val: Self) -> Result { + if Weak::strong_count(&val.finalize_callbacks) == 0 { + return Err(Error::new( + Status::GenericFailure, + format!( + "The original reference that WeakReference<{}> is pointing to is dropped", + std::any::type_name::() + ), + )); + }; let mut result = std::ptr::null_mut(); check_status!( unsafe { crate::sys::napi_get_reference_value(env, val.napi_ref, &mut result) }, @@ -207,6 +216,22 @@ impl WeakReference { Ok(None) } } + + pub fn get(&self) -> Option<&T> { + if Weak::strong_count(&self.finalize_callbacks) == 0 { + None + } else { + Some(unsafe { Box::leak(Box::from_raw(self.raw)) }) + } + } + + pub fn get_mut(&mut self) -> Option<&mut T> { + if Weak::strong_count(&self.finalize_callbacks) == 0 { + None + } else { + Some(unsafe { Box::leak(Box::from_raw(self.raw)) }) + } + } } /// ### Experimental feature