Call function pointer from JNI

人走茶凉 提交于 2019-12-06 08:59:45

问题


I have a function already implemented in cpp with prototype

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

Second argument is a function pointer which must be implemented in java. How can i implement that function? Also how can i call MyFunction in JNI? Please help


回答1:


Try this

  • 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 calling a method in Java through its class instance. In case you do not know the name of java function in advance then function name can be passed as parameter as well.

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




回答2:


In your C++ native code you can simply define a function call Java callback implementation and then pass the function pointer to your native library -- like this:

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));


来源:https://stackoverflow.com/questions/6619980/call-function-pointer-from-jni

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!