Objective C calling Java methods using JNI

Can someone show me how to call a Java method from Objective C.

In more detail this is what I would like to do

1) First call from java side to C object during this call I would like to get a reference to java object.

2) Later in the line, I would like Objective C to use the reference obtained in the previous step to call Java methods.

thank

+2


source to share


1 answer


The following seems to work. It is based on the above comment on the following C examples and this link.

http://urlgrey.net/?p=121

As the link says, don't create a global variable for env, but create a global jvm variable, also create a global reference to your class.

This is how I implement step 1: "1) First call from the java side to the C object. During this call, I would like to get a reference to the java object."

First, declare a global variable in the header file for

1) jvm:

JavaVM *jvm;

      

2) Java class:

jclass smartCallbackClass;

      

3) java object:

jobject smartCallbackObject;

      

Next, in the call that comes from Java to Objective C, set the values ​​for these variables

1) For JVM:



(*env)->GetJavaVM(env, &jvm);

      

2) For an object:

smartCallbackObject = (*env)->NewGlobalRef(env, obj);

      

3) For the class:

if (smartCallbackClass == NULL) {
    jclass localRefCls = (*env)->FindClass(env,"com/studyisland/nativelibs/smart/responsesdk/interfaces/thin/SMARTResponseThinClient"); 
    if (localRefCls == NULL) {
        NSLog(@"Unable to create a JNI Java Class reference \n");
    }
    //Create a global reference for JNI Java class
    smartCallbackClass = (*env)->NewGlobalRef(env,localRefCls);

    //Delete the local reference as it is no longer needed
    (*env)->DeleteLocalRef(env, localRefCls);

    //Is the global reference created successfully?
    if (smartCallbackClass == NULL) {
        NSLog(@"Unable to create JNI Java class reference \n");
        return 0;
    }       
}

      

Here is the link from where I got the code for the class

http://java.sun.com/docs/books/jni/html/refs.html

Now the second step

"2) Later in the line, I would like Objective C to use the reference from the previous step to invoke Java methods."

To call from Objective C back to Java, you need to make sure that the call is done on the same thread that Java is called Objective C by, so here is the code.

-(void)classFailedToStop:(SMARTResponseCallBackEventArg*)anArg{
    JNIEnv *env;
    int attach = (*jvm)->AttachCurrentThread(jvm, (void**)&env, NULL);
    if(attach == 0){
        (*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_4);
        jmethodID method = (*env)->GetMethodID(env, smartCallbackClass, "callback_onStopClassFailed", "()V");
        (*env)->CallVoidMethod(env, smartCallbackObject, method);
    }
    (*jvm)->DetachCurrentThread(jvm);

}

      

Hope this helps.

+4


source







All Articles