JNI Call Function Pointer

I have a function already implemented in cpp with prototype

MyFunction (int size, int (* callback) (UINT16 * arg1, UINT16 * arg2));

The second argument is a pointer to a function to be implemented in java. How can I implement this feature? Also how can I call MyFunction in JNI? Please, help

+2
source share
2 answers

try it

  • Java

    import java.util.*;
    
    public class JNIExample{
    static{
      try{ 
            System.loadLibrary("jnicpplib");
      }catch(Exception e){
         System.out.println(e.toString());
      }
    }
    
    public native void SetCallback(JNIExample jniexample);
    
    public static void main(String args[]){
         (new JNIExample()).go();
    }
    
    public void go(){
        SetCallback(this);
    }
    
     //This will be called from inside the native method    
     public String Callback(String msg){
        return "Java Callback echo:" +msg;
     } 
    }  
    
  • In C ++ native:

    #include "JNIExample.h"
    
    JNIEXPORT void JNICALL Java_JNIExample_SetCallback (JNIEnv * jnienv, jobject jobj, jobject      classref)
    {
       jclass jc = jnienv->GetObjectClass(classref);
       jmethodID mid = jnienv->GetMethodID(jc, "Callback","(Ljava/lang/String;)Ljava/lang/String;");
       jstring result = (jstring)jnienv->CallObjectMethod(classref, mid, jnienv->NewStringUTF("hello jni"));
       const char * nativeresult = jnienv->GetStringUTFChars(result, 0); 
    
       printf("Echo from Setcallback: %s", nativeresult);
    
       jnienv->ReleaseStringUTFChars(result, nativeresult); 
    }
    
  • The idea here is to call a method in Java through an instance of the class. If you do not know the name of the java function in advance, the name of the function can also be passed as a parameter.

: http://www.tidytutorials.com/2009/07/java-native-interface-jni-example-using.html

+3

++ Java, - :

native c++:
// link func
callback_link(int size, int (* callback)(UINT16* arg1, UINT16* arg2)){
  //jni->call Java implementation
}

// call your lib    
MyFunction(int size, int (* callback_link)(UINT16* arg1, UINT16* arg2));
+1

Source: https://habr.com/ru/post/1537525/


All Articles