转载:请注明原地址: http://blog.csdn.net/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:
FindClass
lookups once, in JNI_OnLoad
, and cache the class references for later use. AnyFindClass
calls made as part of executing JNI_OnLoad
will use the class loader associated with the function that called System.loadLibrary
(this is a special rule, provided to make library initialization more convenient). If your app code is loading the library, FindClass
will use the correct class loader.Foo.class
in.ClassLoader
object somewhere handy, and issue loadClass
calls directly. This requires some effort.JNIEnv* env = NULL;
g_jvm->DetachCurrentThread();
既:一个native线程,开始必须调用 AttachCurrentThread. 结束调用 DetachCurrentThread。ClassLoader
object来处理了。
android multithread in c/c++ to call JNI 的第二篇: http://blog.csdn.net/wu4long/article/details/17757433