如果jvm的参数是从其他类型转换的,则jni无法找到该类

时间:2012-11-08 10:55:23

标签: java c++ qt jvm java-native-interface

我有一个jni和c ++ / qt的小问题: 这是我的代码:

void Jvm::create_jvm(QStringList &arguments){
    QTextStream cout(stdout);
    JavaVM *jvm;
    JNIEnv *env;
    JavaVMInitArgs vm_args;
    JavaVMOption *options[4];
    //run begin
    //options[0].optionString = "-Djava.compiler=NONE";
    //options[1].optionString = "-Djava.class.path=app";
    //options[2].optionString = "-verbose:jni";
    //options[3].optionString = "-Xmx512m";
    //run end

    //can't find the class begin
    QByteArray bArray;
    cout<<"Valores del array arguments"<<endl;
    for(int i;i<arguments.size();i++){

        cout<<arguments.at(i)<<endl;
        bArray=arguments.at(i).toStdString().c_str();
        options[i].optionString = bArray.data();
        cout<<options[i].optionString<<endl;
    }
    //can't find the class end


    //jvm args
    vm_args.version = JNI_VERSION_1_6;
    vm_args.nOptions = 4;
    vm_args.options = options;
    vm_args.ignoreUnrecognized = JNI_FALSE;


    jint res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
    if (res < 0) {//jvm don't created
        qDebug()<<"Can't create Java VM\n";
        exit(1);
    }else{//jvm created
        invoke_class(env);
        jvm->DestroyJavaVM();
    }
}

void Jvm::invoke_class(JNIEnv* env) {
    jclass cls;
    jmethodID mainMethod;
    jobjectArray applicationArgs;
    jstring applicationArg0,applicationArg1,applicationArg2;

    //class and main method
    cls = env->FindClass("HolaMundoSwing");
    if (cls == 0) qDebug()<<"Sorry, I can't find the class"; //In case that class not exist
    mainMethod = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");

    //Application arguments array
    applicationArgs = env->NewObjectArray(3, env->FindClass("java/lang/String"), NULL);
    applicationArg0 = env->NewStringUTF("From");
    applicationArg1 = env->NewStringUTF("C");
    applicationArg2 = env->NewStringUTF("program");

    env->SetObjectArrayElement(applicationArgs, 0, applicationArg0);
    env->SetObjectArrayElement(applicationArgs, 1, applicationArg1);
    env->SetObjectArrayElement(applicationArgs, 2, applicationArg2);

    env->CallStaticVoidMethod(cls, mainMethod, applicationArgs); //Call to the method
}

我已经测试过这些论点并且是相同的。 类路径具有相同的值,但注释的代码运行正常而其他代码无法找到类,任何想法?

1 个答案:

答案 0 :(得分:0)

您的for循环包含错误:

for( int i; i < arguments.size(); i++ )

应该是

for( int i = 0; i < arguments.size(); i++ )

否则i将具有任何随机起始值(至少使用我的编译器)