Android jni动态加载so

说到动态加载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);

到此就结束了。如果对你有用请点个赞呗。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

湖中树

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值