From 6735aa868ffb559f82439c55271251ec54ff509e Mon Sep 17 00:00:00 2001 From: Volker Hilsheimer Date: Thu, 12 Oct 2023 16:03:17 +0200 Subject: JNI: add a static getter for a JNIEnv pointer to QJniEnvironment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This further helps reduce the creation of temporary QJniEnivronment instances (with allocated d-pointer) for cases where we simply need to get the JNIEnv for the current thread. Change-Id: I2eda238124be51c755d8910de9dbc9ca8eb92288 Reviewed-by: Tinja Paavoseppä Reviewed-by: Qt CI Bot Reviewed-by: Assam Boudjelthia Reviewed-by: Petri Virkkunen --- src/corelib/kernel/qjnienvironment.cpp | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) (limited to 'src/corelib/kernel/qjnienvironment.cpp') diff --git a/src/corelib/kernel/qjnienvironment.cpp b/src/corelib/kernel/qjnienvironment.cpp index 8d4e386a68..5afa1a6484 100644 --- a/src/corelib/kernel/qjnienvironment.cpp +++ b/src/corelib/kernel/qjnienvironment.cpp @@ -53,10 +53,20 @@ Q_GLOBAL_STATIC(QThreadStorage, jniEnvTLS) QJniEnvironment::QJniEnvironment() : d(new QJniEnvironmentPrivate{}) { + d->jniEnv = getJniEnv(); +} + +/*! + Returns the JNIEnv pointer for the current thread. + + The current thread will be attached to the Java VM. +*/ +JNIEnv *QJniEnvironment::getJniEnv() +{ + JNIEnv *jniEnv = nullptr; + JavaVM *vm = QtAndroidPrivate::javaVM(); - const jint ret = vm->GetEnv((void**)&d->jniEnv, JNI_VERSION_1_6); - if (ret == JNI_OK) // Already attached - return; + const jint ret = vm->GetEnv((void**)&jniEnv, JNI_VERSION_1_6); if (ret == JNI_EDETACHED) { // We need to (re-)attach const QByteArray threadName = QThread::currentThread()->objectName().toUtf8(); @@ -64,12 +74,12 @@ QJniEnvironment::QJniEnvironment() threadName.isEmpty() ? "QtThread" : threadName.constData(), nullptr }; - if (vm->AttachCurrentThread(&d->jniEnv, &args) != JNI_OK) - return; - - if (!jniEnvTLS->hasLocalData()) // If we attached the thread we own it. - jniEnvTLS->setLocalData(new QJniEnvironmentPrivateTLS); + if (vm->AttachCurrentThread(&jniEnv, &args) == JNI_OK) { + if (!jniEnvTLS->hasLocalData()) // If we attached the thread we own it. + jniEnvTLS->setLocalData(new QJniEnvironmentPrivateTLS); + } } + return jniEnv; } /*! -- cgit v1.2.3