i have following .jar library doing simple math operation.
package demo1_lib; /** * * @author tveluppillai */ public class test1 { public int getmath(int num) { return num*100; } }
i have following simple java class consume above .jar library.
import demo1_lib.test1; public class sample2 { public static int intmethod(int n) { test1 obj = new test1(); int res = obj.getmath(n); return res; } }
i able compile above code in following way:
javac -cp test1.jar sample2.java
now, i'm trying consume class in c++ using jni.h approach.
#include "stdafx.h" #include "jni.h" #include <windows.h> using namespace system; int calljava() { javavm *jvm; /* denotes java vm */ jnienv *env; /* pointer 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 null"); } console::read(); return 0; } int main(array<system::string ^> ^args) { calljava(); console::read(); return 0; }
i'm getting following wrong output:
result of intmethod: 0
would please tell me making mistake?