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
62
63
64
65
66
67
68
69
70
71
72
73
/// Constructs a type safe Rust wrapper struct for a JVM class.
macro_rules! jvm_wrapper_struct {
    ($rust_struct_name:ident, $java_type:ident) => (

        /// A Rust wrapper for a JVM class.
        pub struct $rust_struct_name<'a> {

            jvm: &'a Jvm,

            // A non-null pointer to an object in the JVM.
            jvm_ptr: $java_type,
        }

        impl<'a> $rust_struct_name<'a> {

            /// Returns a reference to the JVM object.
            pub fn jvm_ptr(&self) -> &$java_type {
                &self.jvm_ptr
            }

            /// Instantiates the JVM wrapper struct.
            pub fn from_jvm_ptr(jvm: &Jvm, jvm_ptr: $java_type) -> Option<$rust_struct_name> {

                if jvm_ptr.is_null() {
                    return None;
                }

                let jvm_ptr_global = unsafe {

                    // Attach the current native thread to the JVM.
                    let jvm_attachment = JvmAttachment::new(jvm.jvm());

                    // Create a global JVM reference to the given JVM object, to prevent GC from
                    // claiming it.
                    (**jvm_attachment.jni_environment()).NewGlobalRef.unwrap()(
                        jvm_attachment.jni_environment(),
                        jvm_ptr
                    )
                };

                // Could not get the global JVM reference .
                if jvm_ptr_global.is_null() {
                    return None;
                }

                Some(
                    $rust_struct_name {
                        jvm: jvm,
                        jvm_ptr: jvm_ptr_global
                    }
                )
            }
        }

        impl<'a> Drop for $rust_struct_name<'a> {

            fn drop(&mut self) {

                unsafe {

                    // Attach the current native thread to the JVM.
                    let jvm_attachment = JvmAttachment::new(self.jvm.jvm());

                    // Delete the global JVM reference to the JVM object.
                    (**jvm_attachment.jni_environment()).DeleteGlobalRef.unwrap()(
                        jvm_attachment.jni_environment(),
                        self.jvm_ptr
                    );
                }
            }
        }
    )
}