start jvm from c++ using jni
copy some of this from oracle sample code:
1 int _tmain(int argc, _TCHAR* argv[])
2 {
3 JavaVM *jvm; /* denotes a Java VM */
4 JNIEnv *env; /* pointer to native method interface */
5 JavaVMInitArgs vm_args; /* JDK 1.1 VM initialization arguments */
6 JavaVMOption options[2];
7 vm_args.version = 0x00010001; /* New in 1.1.2: VM version */
8 /* Get the default initialization arguments and set the class
9 * path */
10 JNI_GetDefaultJavaVMInitArgs(&vm_args);
11 vm_args.nOptions=1;
12 vm_args.options = options;
13 vm_args.options[0].optionString = "-Djava.class.path=.";
14 vm_args.options[1].optionString = "-verbose:jni";
15
16 /* load and initialize a Java VM, return a JNI interface
17 * pointer in env */
18 JNI_CreateJavaVM(&jvm, (void**)&env, (void**)&vm_args);
19 /* invoke the Main.test method using the JNI */
20 jclass cls = env->FindClass("Main");
21 jmethodID mid = env->GetStaticMethodID(cls, "test", "(I)V");
22 env->CallStaticVoidMethod(cls, mid, 100);
23 /* We are done. */
24 jvm->DestroyJavaVM();
25
26 return 0;
27 }
2 {
3 JavaVM *jvm; /* denotes a Java VM */
4 JNIEnv *env; /* pointer to native method interface */
5 JavaVMInitArgs vm_args; /* JDK 1.1 VM initialization arguments */
6 JavaVMOption options[2];
7 vm_args.version = 0x00010001; /* New in 1.1.2: VM version */
8 /* Get the default initialization arguments and set the class
9 * path */
10 JNI_GetDefaultJavaVMInitArgs(&vm_args);
11 vm_args.nOptions=1;
12 vm_args.options = options;
13 vm_args.options[0].optionString = "-Djava.class.path=.";
14 vm_args.options[1].optionString = "-verbose:jni";
15
16 /* load and initialize a Java VM, return a JNI interface
17 * pointer in env */
18 JNI_CreateJavaVM(&jvm, (void**)&env, (void**)&vm_args);
19 /* invoke the Main.test method using the JNI */
20 jclass cls = env->FindClass("Main");
21 jmethodID mid = env->GetStaticMethodID(cls, "test", "(I)V");
22 env->CallStaticVoidMethod(cls, mid, 100);
23 /* We are done. */
24 jvm->DestroyJavaVM();
25
26 return 0;
27 }
Note:
1. must set path to include jre's bin and \bin\server folder(which has jvm.dll I need), can't copy jvm.dll to exe folder, doesn't work.
2. set include path ($(jdk)\include; $(jdk)\include\win32)
3. add jvm.lib during link
浙公网安备 33010602011771号