在JNI C ++环境中不会触发Java库文件(.jar)

时间:2015-04-28 00:51:15

标签: java c++ methods java-native-interface

我有以下.jar库,用于进行简单的数学运算。

package Demo1_Lib;
/**
 *
 * @author tveluppillai
 */
public class Test1 
{
   public int GetMath(int num)
   {
    return num*100;
   }    
}

我有以下简单的Java类使用上面的.jar库。

import Demo1_Lib.Test1;
public class Sample2
{
   public static int intMethod(int n)
   {
    Test1 obj = new Test1();
     int res = obj.GetMath(n);
     return res;   
   }
 }

我能够通过以下方式编译上述代码:

javac -cp Test1.jar Sample2.java

现在,我正在尝试使用jni.h方法在C ++中使用此类。

 #include "stdafx.h"
 #include "jni.h"
 #include <windows.h>
using namespace System;

int CallJava()
{

  JavaVM *jvm;   /* denotes a Java VM */
  JNIEnv *env;  /* pointer to native method interface */
  jint square;
  HINSTANCE hinstLib;  
  JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */
  JavaVMOption *options = new JavaVMOption[2];

  options[0].optionString = "-Djava.class.path=C:\\TestLib";    
  options[1].optionString = "-Djava.library.path=C:\\TestLib\\Test1.jar";      

  vm_args.version =  JNI_VERSION_1_6;     
  vm_args.options = options;
  vm_args.nOptions = 2;
  vm_args.ignoreUnrecognized = TRUE; */
  hinstLib = LoadLibrary(TEXT("C:\\Program  Files\\Java\\jre1.8.0_45\\bin\\server\\jvm.dll"));

 if(hinstLib==0)
 {
  printf("Error");
  }

 if(hinstLib!= NULL)
 {
   typedef jint (JNICALL *PtrCreateJavaVM)(JavaVM **, void **, void *);

   PtrCreateJavaVM ptrCreateJavaVM =    (PtrCreateJavaVM)GetProcAddress(hinstLib,"JNI_CreateJavaVM");

  int res = ptrCreateJavaVM(&jvm, (void**)&env, &vm_args);    

  jclass cls = env->FindClass("Sample2");   

  jmethodID mid;   

   if(cls !=0)
   {   
   if(cls !=0)
   {   
     mid = env->GetStaticMethodID(cls,"intMethod","(I)I");
     if(mid !=0)
      {  
         square = env->CallStaticIntMethod(cls, mid, 5);       
         printf("Result of intMethod: %d\n", square);
       }      
     }
    }
      jvm->DestroyJavaVM();
   }
   else
  {
   printf("Library is NULL");
  }
   Console::Read();
   return 0;
 }

int main(array<System::String ^> ^args)
{
 CallJava();

 Console::Read();

  return 0;
}

我收到以下 错误输出

intMethod的结果:0

请你告诉我我犯了什么错误?

0 个答案:

没有答案