java - 使用 JNI 在 C++ 中加载 .jar 文件

标签 java c++ spring java-native-interface

我需要将我的 C++(OpenCV 项目)与 Java 代码(一个 Web 服务程序)集成,所以我使用 JNI 来集成它们。

我可以使用 JNI 从 C++ 运行我的 helloWorld Java 代码,如下所示:

import java.io.IOException;

public class Main {

    public Main() {
        System.out.println("hello from no arg");
    }

    public static void main(String[] args) throws IOException {     

    }

    private static void callRestPost2(String ontologyURI, String object, String predicate, String subject) throws IOException {
            java.util.Map<String, Object> params = new java.util.HashMap<String, Object>();//hedef
            params.put("operationType", "insertTriple4TrafficOntology");
            params.put("ontologyURI", ontologyURI);
            params.put("object", object);
            params.put("predicate", predicate);
            params.put("subject", subject);
            System.out.println("Hello World!"); 
     }
}

但是我无法通过使用 JNI 从 C++ 运行具有 .jar 依赖项的 java 代码,它在第 25 行给出错误(我猜是因为来自 spring 框架的新对象 [spring-web-4.2.4 .RELEASE.jar]) 在第 25 行创建)。

import java.io.IOException;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class Main {

    public Main() {
        System.out.println("hello from no arg");
    }

    public static void main(String[] args) throws IOException {     

    }

    private static void callRestPost2(String ontologyURI, String object, String predicate, String subject) throws IOException {
            java.util.Map<String, Object> params = new java.util.HashMap<String, Object>();//hedef
            params.put("operationType", "insertTriple4TrafficOntology");
            params.put("ontologyURI", ontologyURI);
            params.put("object", object);
            params.put("predicate", predicate);
            params.put("subject", subject);
            ResponseEntity<String> entity = null;
            RestTemplate restTemplate = new RestTemplate();
            entity = restTemplate.exchange("http://www.mantam.com.tr/c3po-rest-service/c3pont/insertTriple4TrafficOntology" + "?ontologyURI={ontologyURI}&subject={subject}&object={object}&predicate={predicate}",HttpMethod.POST, null, String.class, params);
             System.out.println(entity.toString());     
    }
}

因此,我的问题是“如何使用 JNI 在 C++ 中加载 .jar 文件?”

我的 C++ 代码:

#include <jni.h>

int main()
{
   Using namespace std;
   JavaVM *jvm;                      // Pointer to the JVM (Java Virtual Machine)
   JNIEnv *env;                      // Pointer to native interface
       //================== prepare loading of Java VM ============================
   JavaVMInitArgs vm_args;                        // Initialization arguments
   JavaVMOption* options = new JavaVMOption[1];   // JVM invocation options
   options[0].optionString = "-Djava.class.path=C:\\Users\\proje\\workspace\\HelloWorld\\bin";   // where to find java .class
   vm_args.version = JNI_VERSION_1_6;             // minimum Java version
   vm_args.nOptions = 1;                          // number of options
   vm_args.options = options;
   vm_args.ignoreUnrecognized = false;     // invalid options make the JVM init fail
       //=============== load and initialize Java VM and JNI interface =============
   jint rc = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);  // YES !!
   delete options;    // we then no longer need the initialisation options. 
   if (rc != JNI_OK) {
          // TO DO: error processing... 
         cin.get();
         exit(EXIT_FAILURE);
   }
      //=============== Display JVM version =======================================
   cout << "JVM load succeeded: Version ";
   jint ver = env->GetVersion();
   cout << ((ver>>16)&0x0f) << "."<<(ver&0x0f) << endl;


    jclass cls2 = env->FindClass("Main");  // try to find the class
    if (cls2 == nullptr) {
        cerr << "ERROR: class not found !";
    }
    else {                                  // if class found, continue
        cout << "Class MyTest found" << endl;
        jmethodID mid2 = env->GetStaticMethodID(cls2, "callRestPost2", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
        if (mid2 == nullptr) {
            cerr << "ERROR: method it main2(int) not found !" << endl;
        }
        else {
            jstring jstr1 = env->NewStringUTF("http://traffic.c3po.mantis.com.tr");
            jstring jstr2 = env->NewStringUTF(c);
            jstring jstr3 = env->NewStringUTF("measured_At");
            jstring jstr4 = env->NewStringUTF("Zevkli_Sokak");
            env->CallStaticVoidMethod(cls2, mid2, jstr1, jstr2, jstr3, jstr4);
            cout << endl;
        }
    }

   jvm->DestroyJavaVM();
   cin.get();
}

最佳答案

我找到了解决方案,现在感到很高兴:)

您应该将完整路径添加到您的 .jar 文件。例如:

options = new JavaVMOption[1];   // JVM invocation options
options[0].optionString =   "Djava.class.path=C:\\Users\\proje\\workspace\\HelloWorld\\bin;C:\\Users\\proje\\workspace\\HelloWorld\\bin\\spring-web-4.2.4.RELEASE.jar;C:\\Users\\proje\\workspace\\HelloWorld\\bin\\spring-core-4.2.4.RELEASE.jar;C:\\Users\\proje\\workspace\\HelloWorld\\bin\\spring-beans-4.2.4.RELEASE.jar;C:\\Users\\proje\\workspace\\HelloWorld\\bin\\commons-logging-1.2.jar";   // where to find java .class and .jar files

就是这样!!!

关于java - 使用 JNI 在 C++ 中加载 .jar 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40911447/

相关文章:

java - length开头的json是什么类型的

java - 在 Java 的 JFileChooser 中选择 'Computer' 或 'Libraries' 会产生一个奇怪的文件对象

java - 有什么方法可以禁用 mockito 的记录调用

java - 我得到 java.lang.NullPointerException : null when I try to initialize the method in Vaadin View

json - Spring Controller 修剪 JSON 数据的建议

C++ 游戏应用程序 UDP 与 TCP

Mac上的c++开发

c++ - 使用模板打印任何容器的所有数据

java - 为代码库设计可扩展实体

java - Spring Boot 2 健康执行器默认映射