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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
use errors::*;
use JNIEnv;
use sys;
use std::ptr;
use std::ops::Deref;
pub struct JavaVM(*mut sys::JavaVM);
unsafe impl Send for JavaVM {}
unsafe impl Sync for JavaVM {}
impl JavaVM {
pub unsafe fn from_raw(ptr: *mut sys::JavaVM) -> Result<Self> {
non_null!(ptr, "from_raw ptr argument");
Ok(JavaVM(ptr))
}
pub fn attach_current_thread(&self) -> Result<AttachGuard> {
let mut ptr = ptr::null_mut();
unsafe {
let res = java_vm_unchecked!(self.0, AttachCurrentThread, &mut ptr, ptr::null_mut());
jni_error_code_to_result(res)?;
let env = JNIEnv::from_raw(ptr as *mut sys::JNIEnv)?;
Ok(AttachGuard {
java_vm: self,
env: env,
})
}
}
pub fn attach_current_thread_as_daemon(&self) -> Result<JNIEnv> {
let mut ptr = ptr::null_mut();
unsafe {
let res = java_vm_unchecked!(
self.0,
AttachCurrentThreadAsDaemon,
&mut ptr,
ptr::null_mut()
);
jni_error_code_to_result(res)?;
JNIEnv::from_raw(ptr as *mut sys::JNIEnv)
}
}
pub fn get_env(&self) -> Result<JNIEnv> {
let mut ptr = ptr::null_mut();
unsafe {
let res = java_vm_unchecked!(self.0, GetEnv, &mut ptr, sys::JNI_VERSION_1_1);
jni_error_code_to_result(res)?;
JNIEnv::from_raw(ptr as *mut sys::JNIEnv)
}
}
}
pub struct AttachGuard<'a> {
java_vm: &'a JavaVM,
env: JNIEnv<'a>,
}
impl<'a> AttachGuard<'a> {
fn detach(&mut self) -> Result<()> {
unsafe {
java_vm_unchecked!(self.java_vm.0, DetachCurrentThread);
}
Ok(())
}
}
impl<'a> Deref for AttachGuard<'a> {
type Target = JNIEnv<'a>;
fn deref(&self) -> &Self::Target {
&self.env
}
}
impl<'a> Drop for AttachGuard<'a> {
fn drop(&mut self) {
match self.detach() {
Ok(()) => (),
Err(e) => debug!("error detaching current thread: {:#?}", e),
}
}
}