38

I have Java application that invokes native C++/C code. The C++/C code needs to callback into Java. Could you give me some examples how to do this.

malat
  • 12,152
  • 13
  • 89
  • 158
garfield
  • 401
  • 1
  • 4
  • 4

1 Answers1

31

There are many valid ways to callback into Java from C/C++. I'm going to show you a technique using C (easy to adjust env for C++) that makes it fairly easy to pass data from native code to Java code. This example passes strings ( easy to modify for any data type ).

In native code, create the following:

// Globals
static jmethodID midStr;
static char * sigStr = "(Ljava/lang/String;ILjava/lang/String;)V";

// Init - One time to initialize the method id, (use an init() function)
midStr = (*env)->GetMethodID(env, class, "javaDefineString", sigStr);

// Methods
static void javaDefineString(JNIEnv * env, jobject o, char * name, jint index, char * value) {
  jstring string = (*env)->NewStringUTF(env, name);
  (*env)->CallVoidMethod(env, o, midStr, string, index, (*env)->NewStringUTF(env, value));
}

In Java code create the following:

Map<String, String>  strings = new HashMap<String, String>();

// Never call this from Java
void javaDefineString(String name, int index, String value) {
  String key = name + "." + index;
  strings.put(key, value);
}

Native usage to send data:

javaDefineString(env, o, "Greet", 0, "Hello from native code");
javaDefineString(env, o, "KeyTimeout", 0, "one second");
javaDefineString(env, o, "KeyTimeout", 1, "two second");

Java usage to receive data:

System.out.println(strings.get("Greet.0");
System.out.println(strings.get("KeyTimeout.0");
System.out.println(strings.get("KeyTimeout.1");
Java42
  • 7,628
  • 1
  • 32
  • 50
  • Hi tried it but this say ..."error: 'javaDefineString' was not declared in this scope". Since it's not JNI method then how can I have declaration in .h header file. Any suggestion? – CoDe Dec 01 '15 at 12:13
  • @Shubh Open a new question and add your code and error info. Chuck – Java42 Dec 01 '15 at 14:34
  • 2
    For those wondering, `class` can be obtained with: `class = (*env)->GetObjectClass(env, o);` – Diego Sep 28 '16 at 10:14
  • Can you do it for a non-static method? – Winter Oct 12 '18 at 12:43