1 use std::marker::PhantomData; 2 3 use crate::sys::jobject; 4 5 /// Wrapper around `sys::jobject` that adds a lifetime. This prevents it from 6 /// outliving the context in which it was acquired and getting GC'd out from 7 /// under us. It matches C's representation of the raw pointer, so it can be 8 /// used in any of the extern function argument positions that would take a 9 /// `jobject`. 10 /// 11 /// Most other types in the `objects` module deref to this, as they do in the C 12 /// representation. 13 #[repr(transparent)] 14 #[derive(Clone, Copy, Debug)] 15 pub struct JObject<'a> { 16 internal: jobject, 17 lifetime: PhantomData<&'a ()>, 18 } 19 20 impl<'a> ::std::ops::Deref for JObject<'a> { 21 type Target = jobject; 22 deref(&self) -> &Self::Target23 fn deref(&self) -> &Self::Target { 24 &self.internal 25 } 26 } 27 28 impl<'a> JObject<'a> { 29 /// Creates a [`JObject`] that wraps the given `raw` [`jobject`] 30 /// 31 /// # Safety 32 /// 33 /// Expects a valid pointer or `null` from_raw(raw: jobject) -> Self34 pub unsafe fn from_raw(raw: jobject) -> Self { 35 Self { 36 internal: raw, 37 lifetime: PhantomData, 38 } 39 } 40 41 /// Unwrap to the internal jni type. into_raw(self) -> jobject42 pub fn into_raw(self) -> jobject { 43 self.internal 44 } 45 46 /// Creates a new null object null() -> JObject<'a>47 pub fn null() -> JObject<'a> { 48 unsafe { Self::from_raw(std::ptr::null_mut() as jobject) } 49 } 50 } 51 52 impl<'a> std::default::Default for JObject<'a> { default() -> Self53 fn default() -> Self { 54 Self::null() 55 } 56 } 57