0

我在实例化 JVM 时遇到了一些问题。如果我独立运行下面的代码,它工作正常。但是,我需要将它集成到一个更大的工具中,该工具将调用一个 java 库。

该程序最初调用 createVM 方法,然后调用 invokePrismWrapper 方法。但是,方法 JNI_CreateJavaVM(...) 返回 JNI_ERR。

预处理器

#define USER_CLASSPATH ".:../ ....

创建虚拟机函数

JNIEnv* createVM (JavaVM **jvm)
{
  JNIEnv *env;                       /* pointer to native method interface */
  JavaVMInitArgs vm_args;            /* JDK/JRE 6 VM initialization arguments */
  JavaVMOption* options = new JavaVMOption[1]; //holds various JVM optional settings
  options[0].optionString = const_cast<char*>("-Djava.class.path="USER_CLASSPATH);
  vm_args.version = JNI_VERSION_1_6;         //version of Java platform 
  vm_args.nOptions = 1;     
  vm_args.options = options;    
  vm_args.ignoreUnrecognized = false;   
  /* load and initialize a Java VM, return a JNI interface * pointer in env */
  long status = JNI_CreateJavaVM(jvm, (void**)&env, &vm_args);

  if (status == JNI_ERR){
    cout << "\n Unable to load JVM \n Exit";
    exit(-1);
  }

  delete options;
  return env;
}

调用PrismWrapper 方法

float invokePrismWrapper(JavaVM **jvm, JNIEnv *env){
  jclass    mainClass       = env->FindClass(MainClass);    //Returns a class object from a fully-qualified name, or NULL if the class cannot be found.
  jmethodID classConstructor    = env->GetMethodID(mainClass, "<init>", "()V"); //Returns the method ID for an instance (nonstatic) method of a class 
  jobject   classObject     = env->NewObject(mainClass, classConstructor); //Constructs a new java object

  float outcome = 0;

  if (mainClass!=0){
   jmethodID methodid = env->GetMethodID(mainClass, "goPrism", "()Ljava/lang/String;");
   if (methodid!=0){
        jstring result = (jstring)env->CallObjectMethod(classObject, methodid); //returns the result of the calling method, an object 
        const jbyte *str = (jbyte *)(env)->GetStringUTFChars(result, NULL);  // Returns a pointer to an array of bytes representing the string in modified UTF-8 encoding
        outcome = ::atof((char*)str);
        env->ReleaseStringUTFChars(result, (char*)str);
        cout << "Result: " << outcome << endl;
   }
   else{
       cout << "Method not found!" << endl;
   }
    return outcome;
  }
  else{
    cout << "Class Not found" << endl;
    return -1;  
  }
}

CMakeLists.txt

cmake_minimum_required(VERSION 2.8.6)

FIND_PACKAGE(JNI REQUIRED)

SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/usr/lib/jvm/java-6-openjdk-amd64/include -I/usr/lib/jvm/java-6-openjdk-amd64/include/linux -L/usr/lib/jvm/java-6-openjdk-amd64/jre/lib/amd64/server")

SET(CMAKE_EXE_LINKER_FLAGS "-ljvm")

# add the binary tree directory to the search path for include files
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
INCLUDE_DIRECTORIES(${JNI_INCLUDE_DIRS})

ADD_LIBRARY(PRISMLibrary SHARED JNIWrapper.cpp)

message("JNI:- " ${JNI_LIBRARIES})
message("Source Dir: - " ${PROJECT_SOURCE_DIR})

TARGET_LINK_LIBRARIES (PRISMLibrary ${JNI_LIBRARIES})

任何帮助是极大的赞赏。

4

0 回答 0