尝试这个修改后的示例,我的Java代码依赖于其他库,这些库已添加到C ++应用程序的根目录中的libs文件夹中。
但是,
jclass mClass = env-> FindClass(“ MyClass”);
返回空值
我怀疑是问题所在
options [0] .optionString =“ -Djava.class.path =。; ./ libs / *。jar”;
因此,我的MyClass.class与C ++解决方案处于同一级别,其余的依赖库位于名为/ libs的文件夹中。
当我使用没有依赖性的java示例类时,发现该类没有问题。
int main()
{
using namespace std;
// Pointer to the JVM (Java Virtual Machine)
JavaVM *jvm;
// Pointer to native interface
JNIEnv *env;
//==================== prepare loading of Java VM ============================
// Initialization arguments
JavaVMInitArgs vm_args;
// JVM invocation options
JavaVMOption* options = new JavaVMOption[1];
// where to find java .class
options[0].optionString = "-Djava.class.path=.;./libs/*.jar";
// minimum Java version
vm_args.version = JNI_VERSION_1_6;
// number of options
vm_args.nOptions = 1;
vm_args.options = options;
// invalid options make the JVM init fail
vm_args.ignoreUnrecognized = false;
//================= load and initialize Java VM and JNI interface ===============
jint rc = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
delete options;
if (rc != JNI_OK)
{
if (rc == JNI_EVERSION)
cerr << "FATAL ERROR: JVM is outdated and doesn't meet requirements" << endl;
else if (rc == JNI_ENOMEM)
cerr << "FATAL ERROR: not enough memory for JVM" << endl;
else if (rc == JNI_EINVAL)
cerr << "FATAL ERROR: invalid argument for launching JVM" << endl;
else if (rc == JNI_EEXIST)
cerr << "FATAL ERROR: the process can only launch one JVM an not more" << endl;
else
cerr << "FATAL ERROR: could not create the JVM instance (error code " << rc << ")" << endl;
cin.get();
exit(EXIT_FAILURE);
}
jint ver = env->GetVersion();
cout << "JVM load succeeded. \nVersion ";
cout << ((ver >> 16) & 0x0f) << "." << (ver & 0x0f) << endl;
//========== Find Class ==========================
// Try to find the class
jclass mClass = env->FindClass("MyClass");
if (mClass == nullptr)
{
cerr << "ERROR: class not found !";
exit(EXIT_FAILURE);
}
cout << "Class MyTest found" << endl;