我有下面的.jar库来做一个简单的数学运算。
package Demo1_Lib;
/**
*
* @author tveluppillai
*/
public class Test1
{
public int GetMath(int num)
{
return num*100;
}
}
我在上面的.jar库中使用了以下简单的java类。
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
你能告诉我我在哪里犯的错吗?
暂无答案!
目前还没有任何答案,快来回答吧!