1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use jni_sys::jobject;
use jvm::Jvm;
use jvm_attachment::JvmAttachment;


/// Represents an object in the JVM.
pub struct JvmObject<'a> {

    jvm: &'a Jvm,

    // Guaranteed not to be a null pointer.
    jvm_object_ptr: jobject,
}

impl<'a> JvmObject<'a> {

    ///
    pub fn jvm_object_ptr(&self) -> &jobject {
        &self.jvm_object_ptr
    }

    ///
    pub fn new(jvm: &Jvm, jvm_object_ptr: jobject) -> Option<JvmObject> {

        if jvm_object_ptr.is_null() {
            return None;
        }

        // Create a global JVM reference to the given JVM object, to prevent GC claiming it.
        let jvm_object_ptr_global = unsafe {
            let jvm_attachment = JvmAttachment::new(jvm.jvm());
            (**jvm_attachment.jni_environment()).NewGlobalRef.unwrap()(jvm_attachment.jni_environment(), jvm_object_ptr)
        };

        if jvm_object_ptr_global.is_null() {
            return None;
        }

        Some(
            JvmObject {
                jvm: jvm,
                jvm_object_ptr: jvm_object_ptr_global
            }
        )
    }
}


impl<'a> Drop for JvmObject<'a> {
    fn drop(&mut self) {

        // Delete the global JVM reference to the JVM object.
        unsafe {
            let jvm_attachment = JvmAttachment::new(self.jvm.jvm());

            (**jvm_attachment.jni_environment()).DeleteGlobalRef.unwrap()(
                jvm_attachment.jni_environment(), self.jvm_object_ptr
            );
        }
    }
}