I'm working on a project where some Java functions must be called from C++ code using JNI. I've tried that with a simple Java class, but when I'm starting to use extra .jar
in my Java project JNI's FindClass
function can't find my class. I've done some research and read about classpath
which is needed for compiling .java file if it uses extra libs, but FindClass
returns null
in that case. Here's basic structure of my code
JavaVMOption options[2];
JNIEnv *env;
JavaVM *jvm;
JavaVMInitArgs vm_args;
long status;
jclass cls;
jmethodID mid;
jint square;
jboolean not;
options[0].optionString = "-Djava.class.path=<path_to_my_java_class>";
options[1].optionString = "-Djava.library.path=<path_to_my_jar_file>";
memset(&vm_args, 0, sizeof(vm_args));
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 2;
vm_args.options = options;
status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
if (status != JNI_ERR)
{
cls = env->FindClass("package/ClassName"); //returns null while using jar
if(cls != 0)
{
//do some stuff
}
jvm->DestroyJavaVM();
return 0;
}
else
return -1;
Any ideas?
UPDATED: I've also tried
options[0].optionString = "-Djava.class.path=<path_to_my_java_class>;<path_to_jar>";
options[0].optionString = "-Djava.class.path=<path_to_my_java_class>";
options[1].optionString = "-classpath <path_to_jar>";
I think that your mistake is that you are putting a JAR on the "library.path". The library path is the path for finding native libraries ... not JAR files.
You should put the JAR file on the classpath; e.g.
options[0].optionString =
"-Djava.class.path=<path_to_my_java_class>:<path_to_my_jar_file>";
(On Windows, use ";" as the classpath separator instead of ":".)
I figured out, that there were 2 problems
1) path_to_my_jar_file
This path must point to the jar file and not to the directory folder which contains it.
2) -Djava.library.path
Comments of Drew McGowen and answer of Stephen C were right - path to jar file must be like they said.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With