NDK开发第一课:环境配置与第一个JNI程序

一、JNI 与 NDK

1. JNI 是什么

    JNI 是 Java Native Interface 的缩写,即 Java 的本地接口。
    目的是使得 Java 与本地其他语言(如 C/C++)进行交互。
    JNI 是属于 Java 的,与 Android 无直接关系。

2. NDK 是什么

    NDK 是 Native Development Kit 的缩写,是 Android 的工具开发包。
    作用是快速开发 C/C++ 的动态库,并自动将动态库与应用一起打包到 apk。
    NDK 是属于 Android 的,与 Java 无直接关系。

3. JNI 与 NDK 的关系

    JNI 是实现的目的,NDK 是 Android 中实现 JNI 的手段。


二、NDK 的下载

1. 官网下载

    地址为:https://developer.android.com/ndk/downloads/
    下载后直接解压即可,注意路径名不能带有中文或者空格。

2. Android Studio 中下载

    点开 Android Studio 的 SDK Manager 可以看到如下截图,这里我们选择下载红框中勾选的3个工具。


  • CMake:一个跨平台的编译构建工具,替代 Android.mk
  • LLDB:一个高效的 C/C++ 的调试工具
  • NDK:即我们需要下载的工具,会生成到 SDK 根目录下的 ndk-bundle 目录下


三、我的第一个 JNI 程序

1. 新建工程,并选择包含 C++ support,如下图所示

    在接下来向导中的 Customize C++ Support 部分,您可以使用下列选项自定义项目:

  • C++ Standard:使用下拉列表选择您希望使用哪种 C++ 标准。选择 Toolchain Default 会使用默认的 CMake 设置。
  • Exceptions Support:如果您希望启用对 C++ 异常处理的支持,请选中此复选框。如果启用此复选框,Android Studio 会将 -fexceptions 标志添加到模块级 build.gradle 文件的 cppFlags 中,Gradle 会将其传递到 CMake。

  • Runtime Type Information Support:如果您希望支持 RTTI,请选中此复选框。如果启用此复选框,Android Studio 会将 -frtti 标志添加到模块级 build.gradle 文件的 cppFlags 中,Gradle 会将其传递到 CMake。

2. Android Studio 会自动帮你生成一个可执行的 Hello World 程序,我们简单看一下这个工程

    相比平常的 Android 工程,这里主要是多了上面截图中红框处的文件。其中 cpp 目录就是我们的 C/C++ 代码、预编译库的默认路径了,而 CMakeList.txt 就是编译的脚本文件了。

    接下来我们详细分析一下每一块的原理。

3. MainActivity

public class MainActivity extends AppCompatActivity {
 
    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
    }
 
    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
}

    我们知道,Java 调用本地方法,是使用 native 关键字。而本例中,本地方法的实现是在一个叫做 “native-lib” 的动态库里(动态库的名称是在 CMakeList.txt 中指定的),要想使用这个动态库,就必须先加载这个库,即 System.loadLibrary(native-lib) 。这些都是 Java 的语法定义。

4. native-lib.cpp

#include <jni.h>
#include <string>
 
extern "C" JNIEXPORT jstring
 
JNICALL
Java_com_afei_jnidemo_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

    上面提到的 public native String stringFromJNI() 方法的实现就是在这里,那怎么知道 Java 中的某个 native 方法是对应的 cpp 中的哪个方法呢?这就和 JNI 的注册有关了,本例中使用的是静态注册,即 “Java包名类名_方法名” 的形式,其中包名也是用下划线替代点号。

    后续章节将详细介绍 JNI 方法的注册,以及参数的转换等。

5. 整个调用流程就是:

  1. Gradle 调用您的外部构建脚本 CMakeLists.txt。
  2. CMake 按照构建脚本中的命令将 C++ 源文件 native-lib.cpp 编译到共享的对象库中,并命名为 libnative-lib.so,Gradle 随后会将其打包到 APK 中。
  3. 运行时,应用的 MainActivity 会使用 System.loadLibrary() 加载原生库。现在,应用可以使用库的原生函数 stringFromJNI()

  4. MainActivity.onCreate() 调用 stringFromJNI(),这将返回“Hello from C++”并使用这些文字更新 TextView。


四、 CMakeList.txt 简单分析

1. 首先我们看一下自动生成的 CMakeList.txt 都有些什么内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# For more information about using CMake with Android Studio, read the
  
# Sets the minimum version of CMake required to build the native library.
  
cmake_minimum_required(VERSION 3.4.1)
  
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
  
add_library(  # Sets the name of the library.
              native-lib
  
              # Sets the library as a shared library.
              SHARED
  
              # Provides a relative path to your source file(s).
              src /main/cpp/native-lib .cpp )
  
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
  
find_library(  # Sets the name of the path variable.
               log-lib
  
               # Specifies the name of the NDK library that
               # you want CMake to locate.
               log )
  
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
  
target_link_libraries(  # Specifies the target library.
                        native-lib
  
                        # Links the target library to the log library
                        # included in the NDK.
                        ${log-lib} )

2. cmake_minimum_required

    指定 Cmake 需要的最低版本

3. add_library

    创建和命名该库,第一个参数是库的名字,例如取名为 native-lib,将会生成一个命名为 libnative-lib.so 的库。
    第二个参数是指定库的类型,一般为 SHARED,即动态库(以 .so 为后缀),还有一种是静态库 STATIC,即静态库(以 .a 为后缀)。
    第三个参数是指定该库使用的源文件路径。
    使用多个 add_library() 命令,您可以为 CMake 定义要从其他源文件构建的更多库。

4. find_library

    找到一个 NDK 的库,并且将这个库的路径存储在一个变量中。例如上例中是找到 NDK 中的 log 库(Android 特定的日志支持库),并将其路径存储在 “log-lib” 变量中,在后面你就可以通过 “${log-lib}” 命令取出变量中的值了。

    关联库。将指定的库关联起来 。

6. 注释应该基本也能看得懂,关于 CMake 的更多语法,将在后续章节介绍。

猜你喜欢

转载自blog.csdn.net/afei__/article/details/80897404
今日推荐