使用 JNI 我试图从 C++ 项目创建 Java 类的实例,但它失败了。我用一个简单的 Java 类测试了相同的代码,它可以工作。不同之处在于我的实际类路径是一个包含一堆 jar 的目录。我需要实例化 CmaesClient
的类属于这些 jar 之一。
这是 C++ 代码:
JavaVM* jvm = NULL;
JNIEnv *env = NULL;
JavaVMInitArgs vm_args;
JavaVMOption* options = new JavaVMOption[1];
options[0].optionString = "-Djava.class.path=/home/azg/code/hpcmom/target/1.1.9-SNAPSHOT/hpcmom-cmaes";
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.options = options;
vm_args.ignoreUnrecognized = JNI_TRUE;
JNI_GetDefaultJavaVMInitArgs(&vm_args);
JNI_CreateJavaVM(&jvm, (void**) &env, &vm_args);
if (jvm == NULL) {
std::cout << "Failed creating JVM" << std::endl;
} else {
std::cout << "Succeeded creating JVM" << std::endl;
}
jclass clazz = env->FindClass("com.sfoam.hpcmom.cmaes.CmaesClient");
if (clazz == NULL) {
std::cout << "Failed creating CmaesClient" << std::endl;
} else {
std::cout << "Succeeded creating CmaesClient" << std::endl;
}
jmethodID constr = env->GetMethodID(clazz, "<init>", "([Ljava/lang/String;)V");
jstring jarPath = env->NewStringUTF("/home/azg/code/hpcmom/target/1.1.9-SNAPSHOT/hpcmom-cmaes/hpcmom-cmaes-1.1.9-SNAPSHOT.jar");
jobject object = env->NewObject(clazz, constr, jarPath);
delete options;
jvm->DestroyJavaVM();
错误意味着它找不到类,因此加载类似乎有问题或?
Succeeded creating JVM
Failed creating CmaesClient
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007f5601067214, pid=25496, tid=140007371831104
#
# JRE version: Java(TM) SE Runtime Environment (7.0_51-b13) (build 1.7.0_51-b13)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (24.51-b03 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# V [libjvm.so+0x645214] get_method_id(JNIEnv_*, _jclass*, char const*, char const*, bool, Thread*)+0x84
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /home/azg/code/sfoml/debug/hs_err_pid25496.log
#
# If you would like to submit a bug report, please visit:
# http://bugreport.sun.com/bugreport/crash.jsp
#
Aborted (core dumped)
目录 /home/azg/code/hpcmom/target/1.1.9-SNAPSHOT/hpcmom-cmaes
包含所有需要的 jar。
最佳答案
name
: a fully-qualified class name (that is, a package name, delimited by “/
”, followed by the class name).
改变
env->FindClass("com.sfoam.hpcmom.cmaes.CmaesClient");
到
env->FindClass("com/sfoam/hpcmom/cmaes/CmaesClient");
(即用 /
替换每个 .
)。
关于java - 通过 JNI 从 C++ 应用程序创建 JVM 后找不到类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21903741/