问题描述
我有一个调用本地C ++ / C代码的Java应用程序。 C ++ / C代码需要回调到Java。
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.
推荐答案
有很多有效的方法可以从C / C ++回调到Java中。我将向你展示一个使用C(易于调整env为C ++)的技术,这使得相当容易地将数据从本机代码传递到Java代码。
此示例传递字符串(对任何数据类型都很容易修改)。
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));
}
在Java代码中创建以下内容:
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);
}
发送数据的本机用法:
javaDefineString(env, o, "Greet", 0, "Hello from native code");
javaDefineString(env, o, "KeyTimeout", 0, "one second");
javaDefineString(env, o, "KeyTimeout", 1, "two second");
用于接收数据的Java用法:
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");
这篇关于JNI - 如何从C ++或C回调到Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!