How to call java method from jni side?

后端 未结 1 833
忘掉有多难
忘掉有多难 2021-01-23 14:03

I have done some c-code functions in jni side, and all workings fine.

public native String getMessage() 

function is returning string from jni

1条回答
  •  粉色の甜心
    2021-01-23 14:11

    My suggestion :

    Create a class which will receive the string (you can also use an interface or an abstract class) :

    class ResultHandler { 
        public void onReturnedString(String str) 
        { 
            /* Do something with the string */ 
        } 
    }
    

    Then change the prototype of your function :

    public native void getMessagewithoutReturn(ResultHandler handler);
    

    and the native function will become :

    void  Java_com_foo_bar_getMessagewithoutReturn(JNIEnv *env, jobject thiz, jobject handler);
    

    Now you have to call the onReturnedString of the handler so you have to use JNI functions:

     jmethodID mid;
     jclass handlerClass = (*env)->FindClass(env, "com/foo/bar/ResultHandler");
     if (handlerClass == NULL) {
         /* error handling */
     }
     mid = (*env)->GetMethodID(env, handlerClass, "onReturnedString", "(Ljava/lang/String;)V");
     if (mid == NULL) {
         /* error handling */
     }
    

    Then when you need to call the function : (I suppose that resultString is a jstring)

     (*env)->CallVoidMethod(env, handler, mid, resultString);
    

    I have not tested the code but you have the basic ideas.

    Some references and sample code here

    0 讨论(0)
提交回复
热议问题