零声大学生春招秋招Linux C/C++开发就业
JNIEnv
这个是JNIEnv是可以用来新建Java对象实例并调用对象方法的。值得注意的地方有两个:
这个JNIEnv必须每次调用时都要重新获取。
在C环境下创建的子线程中,获取JNIEnv必须要AttachCurrentThread
例子如下:
JNIEnv *NZJNI_GetEnv(){
JNIEnv *env = nullptr;
if (g_javavm) {
if (g_javavm->GetEnv((void **)(&env), JNI_VERSION_1_6) != JNI_OK) {
NZLOGE("NZJNI_GetEnv can't get the enviroument");
}
} else {
NZLOGE("NZJNI_GetEnv null javavm");
}
return env;}JNIEnv *NZJNI_AttachCurrentThread(){
JNIEnv *env = nullptr;
if (g_javavm) {
if (g_javavm->AttachCurrentThread(&env, nullptr) != JNI_OK) {
NZLOGE("NZJNI_AttachCurrentThread can't get the enviroument");
}
} else {
NZLOGE("NZJNI_AttachCurrentThread null javavm");
}
return env;}JNIEnv *NZJNI_AutoAttachAndGetEnv(bool *newAttached){
JNIEnv *env = nullptr;
if (g_javavm) {
jint result = g_javavm->GetEnv((void **) (&env), JNI_VERSION_1_6);
if (result == JNI_OK) {
*newAttached = false;
return env;
} else if (result == JNI_EDETACHED) {
if (g_javavm->AttachCurrentThread(&env, nullptr) == JNI_OK) {
*newAttached = true;
return env;
} else {
NZLOGE("NZJNI_AutoAttachAndGetEnv can't AttachCurrentThread ");
*newAttached = false;
return env;
}
} else {
NZLOGE("NZJNI_AutoAttachAndGetEnv can't GetEnv");
*newAttached = false;
return env;
}
} else {
NZLOGE("NZJNI_AutoAttachAndGetEnv null javavm");
return env;
}}void NZJNI_DetachCurrentThread(){
if (g_javavm) {
if (g_javavm->DetachCurrentThread() != JNI_OK) {
NZLOGE("NZJNI_DetachCurrentThread failure");
}
} else {
NZLOGE("NZJNI_DetachCurrentThread null javavm");
}}