Sample code for using C to call Java VM
I found dozens of guys are looking for the source code to write a exe calling Java VM but few reply messages contain a complete demo. In fact, it also makes me nerve-racking for a couple of days. Now I get a demo program and post it to all, which is small but clear enough to show the idea. To some JNI gurus, it may be trivial, but to the newbie like me, it may be helpful. Of course, you may have to modify some string to run this program on your system.
//How to compile
//cl whatever.c -link jvm.lib
///////////////////////////////////////
#include <stdio.h>
#include <jni.h>
#include <windows.h>
typedef jint (JNICALL CreateJavaVM_t)(JavaVM **pvm, void **env, void *args);
JavaVM* jvm;
JNIEnv* create_vm() {
JNIEnv* env;
JavaVMInitArgs args;
JavaVMOption options[1];
int retval = 0;
CreateJavaVM_t *CreateJavaVM;
HINSTANCE handle;
/* Load the Java VM DLL */
if ((handle = LoadLibrary("c:\\j2sdk1.4.0\\jre\\bin\\client\\jvm.dll")) == NULL)
{
printf("Error:cannot loading JVM");
return NULL;
}
/* Now get the function addresses */
CreateJavaVM = (CreateJavaVM_t *)GetProcAddress(handle, "JNI_CreateJavaVM");
if (CreateJavaVM == NULL)
{
printf("Error: can't find JNI interfaces\n");
return NULL;
}
args.version = JNI_VERSION_1_2;
args.nOptions = 1;
options[0].optionString = "-Djava.class.path=d:\\myprojects\\java\\classes";
args.options = options;
args.ignoreUnrecognized = JNI_FALSE;
retval = CreateJavaVM(&jvm, (void **)&env, &args);
if(retval != 0)
{
printf("Error: cannot create JVM");
return NULL;
}
return env;
}
void invoke_class(JNIEnv* env) {
jclass myClass;
jmethodID mainMethod;
jobjectArray applicationArgs;
jstring applicationArg0;
if(env == NULL) return;
myClass = (*env)->FindClass(env, "Project1/Application1");
if(myClass == NULL)
{
printf("Error: cannot find class\n ");
return;
}
mainMethod = (*env)->GetStaticMethodID(env, myClass, "main", "([Ljava/lang/String;)V");
if(mainMethod == NULL)
{
printf("Error: cannot find method\n ");
return;
}
applicationArgs = (*env)->NewObjectArray(env, 1, (*env)->FindClass(env, "java/lang/String"), NULL);
applicationArg0 = (*env)->NewStringUTF(env, "From-C-program");
(*env)->SetObjectArrayElement(env, applicationArgs, 0, applicationArg0);
(*env)->CallStaticVoidMethod(env, helloWorldClass, mainMethod, applicationArgs);
(*jvm)->DestroyJavaVM(jvm);
}
int main(int argc, char **argv) {
JNIEnv* env = create_vm();
invoke_class( env );
}

