我正在编写一个程序,其中我使用JNI从C++代码调用Java函数。如果我直接使用.class
文件,则我的程序可以正常运行,但是当我将它添加到一个jar文件中时,FindClass
会失败。例如,以下内容可以正常工作:
std::string stdOpt = "-Djava.class.path=<path_to_jar>/dependency.jar;<path_to_class>";
boost::scoped_array<char> opt(new char[stdOpt.size() + 1]);
std::copy(stdOpt.begin(), stdOpt.end(), opt.get());
opt[stdOpt.size()] = '\0';
options[0].optionString = opt.get();
JavaVMInitArgs vm_args;
memset(&vm_args, 0, sizeof(vm_args));
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.options = options;
long status = JNI_CreateJavaVM(&m_pJavaVirtualMachine, (void**)&m_pJavaEnvironment, &vm_args);
if (status != JNI_OK)
throw std::logic_error("Cannot start Java Virtual Machine");
m_class = m_pJavaEnvironment->FindClass("MyClass");
if(m_class == 0)
throw std::logic_error("Cannot find Java class");
但是这一个失败了。
std::string stdOpt = "-Djava.class.path=<path_to_jar>/dependency.jar;<path_to_jar>/myjar.jar";
boost::scoped_array<char> opt(new char[stdOpt.size() + 1]);
std::copy(stdOpt.begin(), stdOpt.end(), opt.get());
opt[stdOpt.size()] = '\0';
options[0].optionString = opt.get();
JavaVMInitArgs vm_args;
memset(&vm_args, 0, sizeof(vm_args));
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.options = options;
long status = JNI_CreateJavaVM(&m_pJavaVirtualMachine, (void**)&m_pJavaEnvironment, &vm_args);
if (status != JNI_OK)
throw std::logic_error("Cannot start Java Virtual Machine");
m_class = m_pJavaEnvironment->FindClass("MyClass"); //m_class=NULL
if(m_class == 0)
throw std::logic_error("Cannot find Java class"); //throwing exception
当我尝试从 .jar
中获取 Java 类时,是否有任何差异?出了什么问题?有什么想法吗?
dependency.jar
中查找类会发生什么?FindClass()
方法是否成功? - c.s.