gpt4 book ai didi

java - 使用 JNI 在 .jar 中查找 Java 类

转载 作者:太空狗 更新时间:2023-10-29 20:04:39 25 4
gpt4 key购买 nike

我正在编写一个程序,我在其中使用 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 类时,我应该做些什么?怎么了?有什么想法吗?

最佳答案

如果您的类在包中,请将包包含在对 FindClass 的调用中,而不是类路径中。

 m_class = m_pJavaEnvironment->FindClass( "com/mycompany/mypackage/MyClass" );

关于java - 使用 JNI 在 .jar 中查找 Java 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18212286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com