OK, I have a working version, which required a couple of minor changes:
#include <jni.h>
JNIEnv* create_vm(JavaVM** jvm)
{
JNIEnv* env;
JavaVMInitArgs vm_args;
JavaVMOption options;
options.optionString = "-Djava.class.path=<**add the path to your java program here**>";
vm_args.version = JNI_VERSION_1_8;
vm_args.nOptions = 1;
vm_args.options = &options;
vm_args.ignoreUnrecognized =0;
int res= JNI_CreateJavaVM(jvm, (void**)&env, &vm_args);
if (res < 0)
{
printf("Error code:%d\n", res);
}
return env;
}
int main()
{
JNIEnv* env;
JavaVM* jvm;
env = create_vm(&jvm);
if (env == NULL)
{
printf("Failed to get env"); return 1;
}
jclass cls = (*env)->FindClass(env, "Main"); if (cls != NULL)
{
printf("Found the class");
jmethodID jmid = (*env)->GetStaticMethodID(env, cls, "main", "([Ljava/lang/String;)V"); if (jmid != NULL)
{
(*env)->CallStaticVoidMethod(env, cls, jmid, NULL);
printf("env->CallStaticVoidMethod returned\n");
}
}
else
{
printf("\nUnable to find the requested class\n");
}
return 0;
}
GetStaticMethodID
requires the name and signature of the method to search for. The signature is correct for the sample below.
That works with the following Java program whose class file is stored in the location indicated by the path set in the
options.optionString
above.
import java.io.*;
@SuppressWarnings("unused")
class Main {
public static void main(String[] argv) {
System.out.println("This message should appear on the console");
}
}