JNI:你是如何处理FindClass失败的?

时间:2018-03-08 19:05:16

标签: java exception segmentation-fault java-native-interface sigsegv

我有一个JNI库,可以在加载时执行许多代码块:

jclass id_Collection = global_ref_to_class(env, "java/util/Collection");
jmethodID id_Collection_add = env->GetMethodID(ids.Collection, "add", "(Ljava/lang/Object;)Z");
jmethodID id_Collection_iterator = env->GetMethodID(ids.Collection, "iterator", "()Ljava/util/Iterator;");

其中global_ref_to_class是一个包裹env->FindClass的辅助函数:

jclass global_ref_to_class(JNIEnv* env, string name) {
    jclass class_id = env->FindClass(name.c_str());

    // We need to store a Java 'global reference' to the class to stop it being moved.
    jclass result = static_cast<jclass>(env->NewGlobalRef(class_id));
    env->DeleteLocalRef(class_id);

    return result;
}

现在,env->FindClass失败时会出现问题。特别是:

当运行时找不到java标准库时,后续调用env->GetMethodID会导致段错误

我在网上找不到的代码示例都没有处理这种情况。我打算通过每个块并修改为

jclass id_Collection = global_ref_to_class(env, "java/util/Collection");
if(id_Collection != NULL) {
    jmethodID id_Collection_add = env->GetMethodID(ids.Collection, "add", "(Ljava/lang/Object;)Z");
    jmethodID id_Collection_iterator = env->GetMethodID(ids.Collection, "iterator", "()Ljava/util/Iterator;");
}

?这感觉非常笨重...

帮助人们搜索:错误可以是EXCEPTION_ACCESS_VIOLATION,SIGSEGV,具体取决于系统。

0 个答案:

没有答案