aboutsummaryrefslogtreecommitdiffstats
path: root/java/jni/JNIMem.hpp
diff options
context:
space:
mode:
authorPetre Eftime <[email protected]>2016-06-24 17:01:33 +0300
committerPetre Eftime <[email protected]>2016-07-01 15:11:25 +0300
commit86130c35d42f86e0ff31fcee600c15ad23198f27 (patch)
treefe08d6a91303657ca402ef21ef2a2851fa177a19 /java/jni/JNIMem.hpp
parent49aa869a052693ccbaff3fff06befd4dd5fb3be7 (diff)
java: Add initial support for Java notifications
Signed-off-by: Petre Eftime <[email protected]>
Diffstat (limited to 'java/jni/JNIMem.hpp')
-rw-r--r--java/jni/JNIMem.hpp65
1 files changed, 65 insertions, 0 deletions
diff --git a/java/jni/JNIMem.hpp b/java/jni/JNIMem.hpp
new file mode 100644
index 0000000..3b20e05
--- /dev/null
+++ b/java/jni/JNIMem.hpp
@@ -0,0 +1,65 @@
+#pragma once
+#include <jni.h>
+#include <stdexcept>
+
+extern JavaVM* vm;
+
+class JNIEnvContainer {
+private:
+ JNIEnv *env = nullptr;
+
+public:
+ JNIEnv *operator*() {
+ attach();
+ return env;
+ }
+
+ JNIEnv *operator->() {
+ attach();
+ return env;
+ }
+
+ JNIEnvContainer() {
+ }
+
+ ~JNIEnvContainer() {
+ detach();
+ }
+
+ void attach() {
+ if (env != nullptr)
+ return;
+ jint err = vm->AttachCurrentThreadAsDaemon((void **)&env, NULL);
+ if (err != JNI_OK)
+ throw std::runtime_error("Attach to VM failed");
+ }
+
+ void detach() {
+ if (env == nullptr)
+ return;
+ vm->DetachCurrentThread();
+ env = nullptr;
+ }
+};
+
+extern thread_local JNIEnvContainer jni_env;
+
+class JNIGlobalRef {
+private:
+ jobject object;
+
+public:
+
+ JNIGlobalRef(jobject object) {
+ this->object = jni_env->NewGlobalRef(object);
+ }
+
+ ~JNIGlobalRef() {
+ jni_env->DeleteGlobalRef(object);
+ }
+
+ jobject operator*() {
+ return object;
+ }
+};
+