Share this page 

Start a JVM from CTag(s): JNI


#include <jni.h>
#include <stdio.h>

int main() {
  JavaVM *vm;
  JNIEnv *env; 
  JavaVMInitArgs vm_args;
  JavaVMOption options[1];   
  options[0].optionString = "-Djava.class.path=c:/myclasses"; 
  vm_args.version = JNI_VERSION_1_2;
  vm_args.options = options;
  vm_args.nOptions = 1;
  vm_args.ignoreUnrecognized = 1;
  jstring jstr; 
  jobjectArray args; 
  jint res = JNI_CreateJavaVM(&vm, (void **)&env, &vm_args);
  if (res < 0) { 
    printf("Can't create Java VM\n"); 
    exit(1);
    } 
  jclass cls = env->FindClass("HelloWorld"); // in c:/myclasses
  if (cls == 0) { 
    printf("HelloWorld class not found\n"); 
    exit(1); 
    } 
  jmethodID mid = 
    env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V"); 
  if (mid == 0) { 
    printf("main() method not found\n"); 
    exit(1); 
    } 
  jstring argString = env->NewStringUTF(""); //empty arg list
  jobjectArray args = 
     env->NewObjectArray(1, env->FindClass("java/lang/String"), jstr); 
  if (args == 0) { 
    printf("Out of memory\n"); 
    exit(1); 
    } 
  env->CallStaticVoidMethod(cls, mid, args); 
  return 0;
}