#include "iostream" #include "jni.h" using namespace std; int main() { int res; JavaVM *jvm; JNIEnv *env; JavaVMInitArgs vm_args; JavaVMOption options[4]; /*设置初始化参数*/ options[0].optionString = "-Djava.compiler=NONE"; options[1].optionString = "-Djava.class.path=."; options[2].optionString = "-verbose:jni"; //用于跟踪运行时的信息 /*版本号设置不能漏*/ vm_args.version=JNI_VERSION_1_6;//jdk版本1.2 vm_args.nOptions = 3; vm_args.options = options; vm_args.ignoreUnrecognized = JNI_TRUE; res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); if (res < 0) { cout<<"Can't create Java VM/n"; exit(1); } cout<<"Good create"<<endl; /*捕捉异常*/ if (env->ExceptionOccurred()) { env->ExceptionDescribe(); return 0; } jclass clazz; //全局变量,用来传递class jobject object; //全局变量,用来传递object jstring jstr; //获得java.lang.String类 clazz=env->FindClass("java/lang/String"); if (clazz ==0 ){ cout << "Class is not found" << endl; exit(-1); } //获得String(String str)构造体 jmethodID mid= env->GetMethodID(clazz,"<init>", "(Ljava/lang/String;)V"); if (mid==0){ cerr<< "GetMethodID Error for class" << endl; exit(-1); } //将字符串封装为jstring。 jstr = env->NewStringUTF("helloworld"); if (jstr == 0) { cerr << "Out of memory" <<endl; exit(-1); } object=env->NewObject(clazz,mid,jstr); /*销毁JAVA虚拟机*/ jvm->DestroyJavaVM(); cout<<"Java VM destory./n"; system("pause"); return 0; }
编译:
XXX.bat
cl Jni.cpp /I "C:/Program Files/Java/jdk1.6.0_03/include" /I "C:/Program Files/Java/jdk1.6.0_03/include/win32" /link "C:/Program Files/Java/jdk1.6.0_03/lib/jvm.lib"
REM 避免无法找到Jvm.dll的错误
set path=C:/Program Files/Java/jre1.6.0_03/bin/client;%path%
start "JNI" Jni /WAIT
pause