在Android Studio 3.1中使用预建的JNI库 [英] Use prebuilt JNI library in Android Studio 3.1

查看:116
本文介绍了在Android Studio 3.1中使用预建的JNI库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我获得了一个共享对象(* .so文件),我需要从我的应用程序中引用该对象.我知道共享对象使用JNI的事实.现在,我有一些Android应用程序开发经验,但没有使用本机代码的经验.我已经在StackOverflow和Google上查看了很多答案,但似乎没有一个适合我的问题.

I was given a shared object (*.so file) that I need to reference from my app. I know for a fact that the shared object uses JNI. Now, I have some experience with Android app development, but none with native code. I have looked at a lot of answers here on StackOverflow and on Google in general, but none seem to fit in my question.

基本上,该共享库用于另一个应用程序,并且我拥有该应用程序的代码,现在我需要在我的应用程序中实现它.我对应该从哪里开始或应该做什么感到迷惑.如果有人可以帮助指导我完成此过程,那就太好了.

Basically, this shared object was for another app, and I have the code for that app, and now I need to implement it in my app. I am lost as to where I should start or what I should do. If anyone can help guide me through this process that would be very nice.

此外,我没有共享对象的源文件或头文件.我确实知道本机方法的名称.

Also, I do not have the source files nor the header files for the shared object. I do know the name of the native method.

推荐答案

如果您没有最初定义这些本机方法的Java源,则通常可以从 .so反向工程必要的本机方法定义. 文件本身.例如,如果库导出Java_com_example_testjni_MainActivity_stringFromJni,则必须添加Java类

If you don't have the Java sources that defined these native methods originally, you can often reverse engineer the necessary native method definitions from the .so file itself. E.g., if the library exports Java_com_example_testjni_MainActivity_stringFromJni, then you must add a Java class

package com.example.thestjni;

class MainActivity {
    public native static String stringFromJni();
}

这不能为 native 方法提供正确的参数或返回类型.另外,您必须猜测是否应将 native 方法声明为 static .

This does not give your the correct parameters or return types for the native methods. Also, you must guess whether the native method should be declared static or not.

为了安全起见,您将向此类添加静态构造函数,以确保已加载库:

To be on the safe side, you will add a static constructor to this class, to make sure the library is loaded:

package com.example.thestjni;

class MainActivity {
    static {
        System.loadLibrary("thirdparty");
    }
    public native static String stringFromJni();
}

您可以根据自己的喜好随意重命名3 rd 派对库,但不能重命名包和类.您不必担心原始Java类是否声明了本机方法 private ,可以在项目中安全地将其声明为 public .

You are free to rename the 3rd party library to your liking, but not the package and not the class. You don't care if the original Java class declared the native method private, you can safely declare it public in your project.

要查找由预构建库 libthirdparty.so 导出的JNI函数的名称,可以使用Android NDK工具链随附的 nm 工具:

To find the names of JNI functions exported by prebuilt library libthirdparty.so, you can use the nm tool provided with Android NDK toolchains:

nm -D libthirdparty.so | grep Java_

这篇关于在Android Studio 3.1中使用预建的JNI库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆