@@ -628,23 +628,28 @@ namespace jni
628
628
}
629
629
630
630
631
+ namespace {
632
+ // Some implementations type the parameter as JNIEnv**, others as void**.
633
+ // See https://bugs.openjdk.java.net/browse/JDK-6569899
634
+ struct JNIEnvCast
635
+ {
636
+ using FunVoid = jint (JavaVM::*)(void **, void *);
637
+ using FunEnv = jint (JavaVM::*)(JNIEnv**, void *);
638
+
639
+ template <typename Fun, typename = std::enable_if_t <std::is_same<Fun, FunVoid>::value>>
640
+ void ** operator ()(JNIEnv** env, Fun) noexcept {
641
+ return reinterpret_cast <void **>(env);
642
+ }
643
+
644
+ template <typename Fun, typename = std::enable_if_t <std::is_same<Fun, FunEnv>::value>>
645
+ JNIEnv** operator ()(JNIEnv** env, Fun) noexcept {
646
+ return env;
647
+ }
648
+ };
649
+ }
650
+
631
651
inline UniqueEnv AttachCurrentThread (JavaVM& vm)
632
652
{
633
- // Some implementations type the parameter as JNIEnv**, others as void**.
634
- // See https://bugs.openjdk.java.net/browse/JDK-6569899
635
- struct JNIEnvCast
636
- {
637
- void ** operator ()(JNIEnv** env, jint (JavaVM::*)(void **, void *))
638
- {
639
- return reinterpret_cast <void **>(env);
640
- }
641
-
642
- JNIEnv** operator ()(JNIEnv** env, jint (JavaVM::*)(JNIEnv**, void *))
643
- {
644
- return env;
645
- }
646
- };
647
-
648
653
JNIEnv* result;
649
654
CheckErrorCode (vm.AttachCurrentThread (JNIEnvCast ()(&result, &JavaVM::AttachCurrentThread), nullptr ));
650
655
return UniqueEnv (result, JNIEnvDeleter (vm));
@@ -662,4 +667,18 @@ namespace jni
662
667
CheckErrorCode (vm.GetEnv (reinterpret_cast <void **>(&env), Unwrap (version)));
663
668
return *env;
664
669
}
670
+
671
+ inline JNIEnv& GetAttachedEnv (JavaVM& vm, version version = jni_version_1_1)
672
+ {
673
+ JNIEnv* env = nullptr ;
674
+ auto code = vm.GetEnv (reinterpret_cast <void **>(&env), Unwrap (version));
675
+
676
+ if (code == JNI_EDETACHED) {
677
+ CheckErrorCode (vm.AttachCurrentThread (JNIEnvCast ()(&env, &JavaVM::AttachCurrentThread), nullptr ));
678
+ } else {
679
+ CheckErrorCode (code);
680
+ }
681
+
682
+ return *env;
683
+ }
665
684
}
0 commit comments