Call function pointer from JNI
I have a function already implemented in cpp with prototype开发者_JAVA技巧
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
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
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));
精彩评论