Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

JNI - How to callback from C++ or C to 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...