From a3d64ab239b40a53c6af1d51428a76ee05fafcd5 Mon Sep 17 00:00:00 2001 From: Malcolm James MacLeod Date: Sun, 30 Dec 2018 14:23:46 +0200 Subject: [PATCH] Implement basic automatic attachment/detachment of c++ threads to JVM. (#405) * Implement basic automatic attachment/detachment of c++ threads to JVM. No side effects if not enabled Compile with -DEXPERIMENTAL_AUTO_CPP_THREAD_ATTACH to enable Requires a compiler with C++11 support Borrows code/idea from https://github.com/dropbox/djinni/issues/372#issuecomment-394629525 * Place assignment outside of define. --- support-lib/jni/djinni_support.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/support-lib/jni/djinni_support.cpp b/support-lib/jni/djinni_support.cpp index 142b9e220..22324e5a6 100644 --- a/support-lib/jni/djinni_support.cpp +++ b/support-lib/jni/djinni_support.cpp @@ -72,7 +72,17 @@ void jniShutdown() { JNIEnv * jniGetThreadEnv() { assert(g_cachedJVM); JNIEnv * env = nullptr; - const jint get_res = g_cachedJVM->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6); + jint get_res = g_cachedJVM->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6); + #ifdef EXPERIMENTAL_AUTO_CPP_THREAD_ATTACH + if (get_res == JNI_EDETACHED) { + get_res = g_cachedJVM->AttachCurrentThread(&env, nullptr); + thread_local struct DetachOnExit { + ~DetachOnExit() { + g_cachedJVM->DetachCurrentThread(); + } + } detachOnExit; + } + #endif if (get_res != 0 || !env) { // :( std::abort();