Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JVM] Automatic Compatibility of JVM AttachCurrentThread #16987

Merged
merged 1 commit into from
May 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
[JVM] Automatic Compatibility of JVM AttachCurrentThread
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 11, 2024
commit e425df51f395b0d46e5086ff562866befc553cc9
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
Loading