Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function pointer from JNI

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

like image 649
indira Avatar asked Apr 15 '26 21:04

indira


1 Answers

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

like image 194
longbkit Avatar answered Apr 17 '26 10:04

longbkit