i encounter a issue that how to callback java method in C method, this c method unlike JNI generate c method. not include JNIEnv and JObject parameter in the parameter list. How to solve it or something else workaround....
2 Answers
To execute a Java method from C program you need to load JVM into C program first. For that you should use the Invocation API, see http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/invocation.html
This method will create its own JNI_CreateJavaVM method and attach it as a thread then releases it right after using it.
Load jvm.dll installed in your computer
TCHAR* dllpath = (char*)TEXT("C:\\Program Files\\Java\\jdk1.8.0_65\\jre\\bin\\server\\jvm.dll");
HMODULE jniModule = LoadLibrary(dllpath);
Define the function to create JVM
typedef int (JNICALL * JNI_CreateJavaVM)(JavaVM** jvm, JNIEnv** env, JavaVMInitArgs* initargs);
JNI_CreateJavaVM createJavaVM = (JNI_CreateJavaVM)GetProcAddress(jniModule, "JNI_CreateJavaVM");
Create the JVM
JavaVMOption* options = new JavaVMOption[1];
options[0].optionString = const_cast<char*>("-Djava.class.path=" USER_CLASSPATH);
JavaVMInitArgs initArgs;
initArgs.version = JNI_VERSION_1_6;
initArgs.nOptions = 1;
initArgs.options = options;
JavaVM* jvm;
JNIEnv* env;
DWORD retval;
if ((retval = createJavaVM(&jvm, &env, &initArgs)) != JNI_OK){
cout << "beyond the scope of this answer" << endl;
return 1;
}
jint retvalue = jvm->GetEnv((void**)&env, JNI_VERSION_1_6);
bool mustDetach = false;
Detach your JVM if necessary
if (retvalue == JNI_EDETACHED)
{
JavaVMAttachArgs args;
args.version = JNI_VERSION_1_6;
args.name = NULL;
args.group = NULL;
retvalue = jvm->AttachCurrentThread((void**)&env, &args);
mustDetach = true; // to clean up afterwards
}
Point to your target Java class where the method is located
jclass clazz = env->FindClass("MyClazz");
Point to the java method
jmethodID mid = env->GetStaticMethodID(clazz, "myJavaMethod", "()I");
Invoke the java method
int returnedValue = env->CallStaticintMethod(clazz, mid);
cout << "Returned value is " << returnedValue->size << endl;
This will not throw undefined reference to JNI_CreateJavaVM