Skip to content

Commit

Permalink
[JVM] Automatic Compatibility of JVM AttachCurrentThread (#16987)
Browse files Browse the repository at this point in the history
Different JDK may have different signature for AttachCurrentThread.
This can cause issues for example between code for android and normal java.
This PR uses a helper class to enable compact with both.
  • Loading branch information
tqchen committed May 12, 2024
1 parent 825dc1f commit 4403379
Showing 1 changed file with 19 additions and 10 deletions.
29 changes: 19 additions & 10 deletions jvm/native/src/main/native/org_apache_tvm_native_c_api.cc
Original file line number Diff line number Diff line change
Expand Up @@ -222,17 +222,30 @@ JNIEXPORT jint JNICALL Java_org_apache_tvm_LibInfo_tvmFuncCall(JNIEnv* env, jobj
return ret;
}

// A helper object to take in JNIEnv ptr
// and allow automatic casting to both JNIEnv** and void**
// Background: different version of JDK may choose to have one signature
// or another for the case of AttachCurrentThread
// we use this universal helper object to enable compatibility with both
class JNIEnvPtrHelper {
public:
explicit JNIEnvPtrHelper(JNIEnv** penv) : penv_(penv) {}

operator JNIEnv**() { return penv_; }

operator void**() { return reinterpret_cast<void**>(penv_); }

private:
JNIEnv** penv_;
};

// Callback function
extern "C" int funcInvokeCallback(TVMValue* args, int* typeCodes, int numArgs,
TVMRetValueHandle ret, void* resourceHandle) {
JNIEnv* env;
int jniStatus = _jvm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6);
if (jniStatus == JNI_EDETACHED) {
#ifdef TVM4J_ANDROID
_jvm->AttachCurrentThread(&env, nullptr);
#else
_jvm->AttachCurrentThread(reinterpret_cast<void**>(&env), nullptr);
#endif
_jvm->AttachCurrentThread(JNIEnvPtrHelper(&env), nullptr);
} else {
CHECK(jniStatus == JNI_OK);
}
Expand Down Expand Up @@ -305,11 +318,7 @@ extern "C" void funcFreeCallback(void* resourceHandle) {
JNIEnv* env;
int jniStatus = _jvm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6);
if (jniStatus == JNI_EDETACHED) {
#ifdef TVM4J_ANDROID
_jvm->AttachCurrentThread(&env, nullptr);
#else
_jvm->AttachCurrentThread(reinterpret_cast<void**>(&env), nullptr);
#endif
_jvm->AttachCurrentThread(JNIEnvPtrHelper(&env), nullptr);
} else {
CHECK(jniStatus == JNI_OK);
}
Expand Down

0 comments on commit 4403379

Please sign in to comment.