Search code examples
javac++java-native-interface

JNI CallStaticObjectMethod return NULL in c++


Here is the code in C++ ,where i create a Java VM and i need to call a function from a jar.

    JavaVM *jvm;       /* denotes a Java VM */
JNIEnv *env;       /* pointer to native method interface */
JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */
jmethodID constr = NULL;
jmethodID Read_XML = NULL;
JavaVMOption* options = new JavaVMOption[1];
options[0].optionString = "-Djava.class.path=<path_to_my_jar>";
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.options = options;
vm_args.ignoreUnrecognized = JNI_TRUE;
/* load and initialize a Java VM, return a JNI interface
 * pointer in env */
long status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
if (status == JNI_ERR){
    cout << "Fail:  Unable to load JVM \t Exit" << endl;
}
 jclass xml_read = env->FindClass("<MyClass>");
 if (env->ExceptionCheck()){
      cout << "Fail:";
 }
 constr = env->GetMethodID(xml_read, "<init>", "()V");
 if (env->ExceptionCheck()){
     cout << "Fail:";
 }
 Read_XML = env->GetStaticMethodID(xml_read,"readFromXML", "(Ljava/lang/String;)L<MyClass>;");
 if (env->ExceptionCheck()){
     cout << "Fail:";
 }
 const char* filepath = "<My_filepath>";
 const jstring file = env->NewStringUTF(filepath);
 jobject ret_obj = env->CallStaticObjectMethod(xml_read,Read_XML,file);
 if (env->ExceptionCheck()){
     cout << "Fail:";
 }

Now the ret_obj is NULL.The Java function i am calling takes a String as argument and returns an Object from another Class different from MyClass.

Java Method is like this public static SomeClass readFromXML(String filepath)

UPDATE 1 Inside the CallStaticObjectMethod we have this jobject CallStaticObjectMethod(jclass clazz, jmethodID methodID, ...) { va_list args; jobject result; va_start(args,methodID); result = functions->CallStaticObjectMethodV(this,clazz,methodID,args); va_end(args); return result; }

After va_start(args,methodID); the value of args is somnething like this 0x002cf5fc "0¦ύ" So maybe there is something with the arguments?


Solution

  • ok this one solved.It was my bad, in filepath i should define the XML file too and not just the file containing this.Thank you