標籤:
對於Android可使用的STL庫有很多,但gnustl功能無疑是最全面。
百度一下,發現很多人對ndk 使用stl庫很不全面,往往gunstl static 過分著墨,因此,我這裡之講述 share庫的使用。
Application.mk
Android.mk
ndkstl.cpp
預先處理一些函數和變數
然後執行代碼
int testVector(){vector<string> catlst;int i = 0;char temp[MAX_BUFFER_SIZE];for (i = 0; i < 10; ++i){memset(temp,0,MAX_BUFFER_SIZE);sprintf(temp,"Category_%d",(i+1));string s(temp);catlst.push_back(temp);}if(!catlst.empty()){ vector<string>::iterator result; result = find(catlst.begin(),catlst.end(),"Category_4"); if(result==catlst.end()) { cout<<"查詢失敗"<<endl; Log::E("STL","查詢失敗"); }else{ cout<<"查詢成功:"<<result-catlst.begin()<<endl; string s("查詢成功"); s.append(":所在位置索引="); char buf[16]; sprintf(buf,"%d",result-catlst.begin()); s.append(buf); Log::E("STL",s.c_str()); }/*for (i = 0; i < catlst.size(); ++i){string item = catlst[i];outPrint(item);}*/ for_each(catlst.begin(),catlst.end(),outPrint); int s1 = catlst.size(); catlst.push_back("Category_4"); if(s1>catlst.size()) { Log::I("Vector","刪除成功"); }else{ Log::I("Vector","刪除曬白"); } catlst.clear();}else{cout<<"vector資料存放區出錯"<<endl; Log::E("STL","vector資料存放區出錯");}}void testMap(){map<string,string> idMap;idMap.insert(pair<string, string>("HX9182", "Zhangsan"));idMap["HO8081"] = "王五";idMap["HX9192"] = "Harfter";}
在java代碼中也要載入stl
static{System.loadLibrary("gnustl_shared");System.loadLibrary("ndkstl");}
此外,說道這裡,對於jni ndk so容錯使用 loadLibrary是有問題
我們在so模組不存在時,可以選擇不調用jni方法,解決方案時適用System.load
//jni so位置在 "/data/data/"+getPackageName()+"/lib/目錄下"
public class MainActivity extends FragmentActivity {private String checkJNISo;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);checkJNISo = checkJNISo("libndkstl.so");if(!TextUtils.isEmpty(checkJNISo)) {System.load(checkJNISo);}}@Overrideprotected void onResume() {super.onResume();if(!TextUtils.isEmpty(checkJNISo)) { `javaMain();}}//用於檢測 so模組是否存在,如果不存在,可以不調用soprivate String checkJNISo(String soName){File filesDir = getFilesDir();if(filesDir!=null){String dataPath = filesDir.getParentFile().getAbsolutePath();//jni so位置在 "/data/data/"+getPackageName()+"/lib/目錄下"File f = new File(dataPath+"/lib/",soName);//"libndkstl.so");if(f!=null && f.exists()){return f.getAbsolutePath();}}return null;}private native void javaMain();static{ System.loadLibrary("gnustl_shared");//System.loadLibrary("ndkstl");}}
[-------------------------------------------------------------]
錯誤解決:
stl 庫預設不是自動載入的,在項目中可能遇到header檔案找不到情況,解決方案
Android NDK STL 庫調與 System.load