[英]Calling a Java function from C++ on Android over JNI
I am calling C++ from Android with JNI and so far it works. 我正在使用JNI从Android调用C ++,到目前为止,它仍然有效。 Now I need in that C++ function some functionality from Java and try to call back to Java from C++. 现在,我需要在C ++函数中使用Java的某些功能,然后尝试从C ++中回调到Java。 I checked various solutions on stackoverflow and other sources on the net but I somehow just couldn't get it working. 我检查了stackoverflow上的各种解决方案以及网络上的其他来源,但是我不知何故无法正常工作。
I always get the following Exception " W/dalvikvm(358): JNI WARNING: can't call Lcom/main/Main;.message on instance of Lcom/main/Main;
" 我总是收到以下异常“ W/dalvikvm(358): JNI WARNING: can't call Lcom/main/Main;.message on instance of Lcom/main/Main;
”
Can anyone give me any advice on this ? 有人可以给我任何建议吗? Did I miss something, oversee something or have just plain wrong code ? 我是否错过了某些东西,是否进行了监督或只是编写了错误的代码?
Here is the Java part that I want to call from C++: 这是我想从C ++调用的Java部分:
public class Main extends Activity
{
public native String JNIInit();
String message(String text)
{ text = text + "from java";
return text;
}
.
.
}
This is the C++ function that I can successfully call from Java but from which I cannot call back to Java: 这是我可以从Java成功调用的C ++函数,但不能从中调用Java:
extern "C" JNIEXPORT jstring JNICALL Java_com_main_Main_JNIInit(JNIEnv* env, jobject obj)
{ jstring jstr = env->NewStringUTF("From jni");
jclass cls = env->FindClass("com/main/Main");
jmethodID method = env->GetMethodID(cls, "message", "(Ljava/lang/String;)Ljava/lang/String;");
jobject result = env->CallObjectMethod(obj, method, jstr);
return env->NewStringUTF(str);
}
PS: I know there are several threads on this topic here, but I couldn't get it working anyway. PS:我知道这里有多个主题,但是无论如何我还是无法使它起作用。 There must be something that I just miss, and I simply can't figure out what that is. 肯定有些东西我只是想念,而我根本无法弄清楚那是什么。
您可以尝试使用以下方法来代替使用FindClass
: (*env)->GetObjectClass(env, obj);
you have use create an empty string in c++ and also pass the empty string from java from the method 您已经使用在c ++中创建一个空字符串,并且还从方法中传递了java中的空字符串
jString pSrc = (*env)->GetString(env,source, 0);
// Here source is the empty string u are passing from the java method now u copy the string into source //这里source是您从java方法传递的空字符串,现在您将字符串复制到source
(*env)->String(env, source, pSrc , 0);
and in the end use 最终用途
(*env)->ReleaseString(env,source, pSrc , 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.