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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With