-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhandle.h
More file actions
37 lines (31 loc) · 943 Bytes
/
handle.h
File metadata and controls
37 lines (31 loc) · 943 Bytes
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
#include <jni.h>
#include <iostream>
#ifndef _HANDLE_H_INCLUDED_
#define _HANDLE_H_INCLUDED_
extern jfieldID getHandleField(JNIEnv *, jobject );
/*
Used to retrieve the object that is represented by the Java object using the handle field
*/
template <typename T>
T *getHandle(JNIEnv *jenv, jobject obj) {
jlong handle = jenv->GetLongField(obj, getHandleField(jenv, obj));
if (jenv->ExceptionCheck()) {
jenv->Throw(jenv->ExceptionOccurred());
return NULL;
}
return reinterpret_cast<T *>(handle);
}
template <typename T>
void setHandle(JNIEnv *jenv, jobject obj, T *t) {
try {
jlong handle = reinterpret_cast<jlong>(t);
jenv->SetLongField(obj, getHandleField(jenv, obj), handle);
if (jenv->ExceptionCheck()) {
jenv->Throw(jenv->ExceptionOccurred());
}
} catch (const std::exception &e) {
jclass exceptionClass = jenv->FindClass("java/lang/RuntimeException");
jenv->ThrowNew(exceptionClass, e.what());
}
}
#endif