I have done some c-code functions in jni side, and all workings fine.
public nativ开发者_StackOverflowe String getMessage()
function is returning string from jni side to java side, and it works fine, and all other jni codes works also fine. But a problem is how can I return string in jni function which without using return , so
public native void getMessagewithoutReturn()
should be able to return string. Then I but getMessagewithoutReturn() function never ending loop using pthread as following you can see: (it works)
pthread_t native_thread;
pthread_create(&native_thread, NULL, native_thread_start_reading, env);
and each loop iteration time I have to be able to return string, so I can't use return, because it stop the function run.
pthread_t native_thread;
pthread_create(&native_thread, NULL, native_thread_start_reading, env);sted out that
I have tested out that posix thread and all works fine in android side, because it's has been not start worker thread, but now just problem to get string in every iteration time, without using function return.
My suggestion :
Create a class which will receive the string (you can also use an interface or an abstract class) :
class ResultHandler {
public void onReturnedString(String str)
{
/* Do something with the string */
}
}
Then change the prototype of your function :
public native void getMessagewithoutReturn(ResultHandler handler);
and the native function will become :
void Java_com_foo_bar_getMessagewithoutReturn(JNIEnv *env, jobject thiz, jobject handler);
Now you have to call the onReturnedString of the handler so you have to use JNI functions:
jmethodID mid;
jclass handlerClass = (*env)->FindClass(env, "com/foo/bar/ResultHandler");
if (handlerClass == NULL) {
/* error handling */
}
mid = (*env)->GetMethodID(env, handlerClass, "onReturnedString", "(Ljava/lang/String;)V");
if (mid == NULL) {
/* error handling */
}
Then when you need to call the function : (I suppose that resultString is a jstring)
(*env)->CallVoidMethod(env, handler, mid, resultString);
I have not tested the code but you have the basic ideas.
Some references and sample code here
精彩评论