转载:请注明原地址: http://blog.youkuaiyun.com/wu4long/article/details/17756419
android的c/c++调用java的代码 都是通过jni的。
但如果你在c/c++新建自己的线程,然后在线程上通过jni调用java的代码,那就麻烦来了。 找不到你需要调用的class。
怎么办?
Android里面有说明,http://developer.android.com/training/articles/perf-jni.html 。
造成这个原因是:
You can get into trouble if you create a thread yourself (perhaps by callingpthread_create and then attaching it with AttachCurrentThread). Now the stack trace looks like this:
dalvik.system.NativeStart.run(Native Method)
The topmost method is NativeStart.run, which isn't part of your application. If you call FindClass from this thread, the JavaVM will start in the "system" class loader instead of the one associated with your application, so attempts to find app-specific classes will fail.
dalvik.system.NativeStart.run(Native Method)
JavaVM将使用系统的class loader而不是你的应用使用的class loader. 从而去找应用自身的类,将会失败。
android也给出了几个解决方案:
There are a few ways to work around this:
- Do your
FindClasslookups once, inJNI_OnLoad, and cache the class references for later use. AnyFindClasscalls made as part of executingJNI_OnLoadwill use the class loader associated with the function that calledSystem.loadLibrary(this is a special rule, provided to make library initialization more convenient). If your app code is loading the library,FindClasswill use the correct class loader. - Pass an instance of the class into the functions that need it, by declaring your native method to take a Class argument and then passing
Foo.classin. - Cache a reference to the
ClassLoaderobject somewhere handy, and issueloadClasscalls directly. This requires some effort.
JavaVM *g_jvm = NULL;
jobject g_obj = NULL;
{
(*env)->GetJavaVM(env,&g_jvm);
g_obj = (*env)->NewGlobalRef(env,obj);
}
JNIEnv* env = NULL;
if(cls == NULL)
{
}
g_jvm->DetachCurrentThread();
既:一个native线程,开始必须调用 AttachCurrentThread. 结束调用 DetachCurrentThread。ClassLoader object来处理了。
android multithread in c/c++ to call JNI 的第二篇: http://blog.youkuaiyun.com/wu4long/article/details/17757433

本文探讨了在Android环境中,C/C++通过JNI调用Java代码时遇到的问题,特别是当涉及多线程操作时。文章详细介绍了由于线程创建不当导致无法找到所需Java类的情况,并提供了几种解决方法,包括在JNI_OnLoad中缓存类引用和通过ClassLoader对象进行类查找。
4430

被折叠的 条评论
为什么被折叠?



