編輯:關於Android編程
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;
if( g_jvm->AttachCurrentThread(&env,NULL) < 0) { /// your error process. } jclass cls = (*env)->GetObjectClass(env,g_obj);g_jvm->DetachCurrentThread();
既:一個native線程,開始必須調用 AttachCurrentThread. 結束調用 DetachCurrentThread。 不建議多次調用 AttachCurrentThread / DetachCurrentThread。否則可能會造成虛擬機的內存洩漏問題。 因為調用 AttachCurrentThread 是java虛擬機要創建java端的線程與之對應。 這個開銷大家自己去想吧。呵呵。因此,一個線程just call one time。ClassLoader
object來處理了。android multithread in c/c++ to call JNI 的第二篇: http://blog.csdn.net/wu4long/article/details/17757433
效果圖:右邊的文字欄上下移動,沒有文字會自動停止移動。這和之前我寫的紋理移動不同,之前的是循環移動,這次是定位移動。頂點著色器: uniform mat4 uM
本文均屬自己閱讀源碼的點滴總結,轉賬請注明出處謝謝。歡迎和大家交流。qq:1037701636 email: [email protected] 在前面的博文
Java初學者直接在Java源碼使用hello 和123 類型的字符串和整型,但時間長了就會忘記當初定義的原因,有經驗的也許會定義字符串常量ResultSet.TYPE_
ListView允許用戶通過手指上下滑動的方式將屏幕外的數據滾動到屏幕內,同時屏幕上原有的數據則會滾動出屏幕.1. ListView的簡單用法首先新建一個ListView