Here is my situation and it's a bit complicated, but it has to be this way. I'm implementing a program from Java that open an application by using JNative. The application is written in C++. But when the application is finished I want it to callback to Java to let Java knows that the run is finished. Can I do that and how? I know I should use JNI but I found no example about that. Thanks.
By "open an application" do you mean launch an external process, or make a library call?
If you're just launching an executable, you can use Runtime.getRuntime().exec
to launch the process, and use the returned process handle to get the return code from the process. You can also capture the output of the process with getInputStream
from the process you launched.
However, if you are actually calling into the C process, then yes, JNI would be a preferred solution. You can find a good tutorial on JNI calls back to Java object here: http://journals.ecs.soton.ac.uk/java/tutorial/native1.1/implementing/method.html
The crux of it from the tutorial is this:
JNIEXPORT void JNICALL
Java_Callbacks_nativeMethod(JNIEnv *env, jobject obj, jint depth)
{
jclass cls = (*env)->GetObjectClass(env, obj);
jmethodID mid = (*env)->GetMethodID(env, cls, "callback", "(I)V");
if (mid == 0)
return;
printf("In C, depth = %d, about to enter Java\n", depth);
(*env)->CallVoidMethod(env, obj, mid, depth);
printf("In C, depth = %d, back from Java\n", depth);
}
In short, from C you need to get the method before you can call it. You can also use the javap tool to generate method signatures so you can call them.