說到動態加載so,優勢就在于可以便捷的進行so的更新,下面說明下,
首先由于動態加載所以不能拷貝到外存盤設備,所以最終是拷貝到**/data/data/PackageName/files**下面:(so是從assets檔案下拷貝到/data/data/…)
拷貝代碼是:
public static void copyData(Context context, String fileName) {
InputStream in = null;
FileOutputStream out = null;
String path = context.getApplicationContext().getFilesDir().getAbsolutePath() + "/"+ fileName; // data/data目錄
File file = new File(path);
if (!file.exists()) {
try {
in = context.getAssets().open(fileName); // 從assets目錄下復制
out = new FileOutputStream(file);
int length = -1;
byte[] buf = new byte[1024];
while ((length = in.read(buf)) != -1) {
out.write(buf, 0, length);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
再然后就是如何在cpp動態加載這個so,頭檔案**#include<dlfcn.h>**
static void *_handle = NULL;
// 創建dlopen句柄
_handle = dlopen("/data/data/$PackageName/files/$SoName", RTLD_LAZY|RTLD_GLOBAL);
//釋放,關閉
if (_handle){
dlclose(_handle);
_handle= NULL;
}
如何使用so里面的函式呢,
假設so里面有個介面為:
int test(int a, int b);
呼叫方式就是這樣:
//_test == T型別
typedef int (*_test)(int a, int b);
_test T_func = NULL;
// 反射加載到方法
T_func = (_version)dlsym(_handle, "test");
// 呼叫函式
int result = T_func(1,2);
到此就結束了,如果對你有用請點個贊唄,
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/230322.html
標籤:其他
