Wednesday 26 June 2013

Java method in a C++ application

The following function allows you to create the VM.
JNIEnv* create_vm(JavaVM ** jvm)
{
    JNIEnv *env;
    JavaVMInitArgs vm_args;
    JavaVMOption options[2];

    options[0].optionString = "-Djava.class.path=.";
    options[1].optionString = "-DXcheck:jni:pedantic";  

    vm_args.version = JNI_VERSION_1_6;
    vm_args.nOptions = 2;
    vm_args.options = options;
    vm_args.ignoreUnrecognized = JNI_TRUE; // remove unrecognized options

    int ret = JNI_CreateJavaVM(jvm, (void**) &env, &vm_args);
    if (ret < 0) printf("\n<<<<< Unable to Launch JVM >>>>>\n");
    return env;
}
Compile the famous Hello World program. The following function attempts to call the main method of the HelloWorld Program.
int main(int argc, char* argv[])
{
    JNIEnv* env;
    JavaVM* jvm;

    env = create_vm(&jvm);

    if (env == NULL) return 1;

    jclass myClass = NULL;
    jmethodID main = NULL;


    myClass = env->FindClass("HelloWorld");


    if (myClass != NULL)
        main = env->GetStaticMethodID(myClass, "main", "([Ljava/lang/String;)V");
    else
        printf("Unable to find the requested class\n");


    if (main != NULL)
    {
       env->CallStaticVoidMethod( myClass, main, " ");

    }else printf("main method not found") ;


    jvm->DestroyJavaVM();
    return 0;
}
Now put create_vm function and main function into a single cpp file, include jni.h and compile it. I used MinGW on windows.
g++ -D_JNI_IMPLEMENTATION_ -I"C:\Program Files\Java\jdk1.6.0_32\include" -I"C:\Program Files\Java\jdk1.6.0_32\include\win32" hello.cpp -L"C:\Program Files\Java\jre6\bin\client" -ljvm -o hello.exe
Exection Now if you run the created exe, you will get an error. jvm.dll not found . Put C:\Program Files\Java\jre6\bin\client in your PATH environment variable. Now you can run the exe file.
Note: Don't displace the jvm.dll file.

No comments:

Post a Comment