初识安卓JNI开发,用Cmake实现JNi的调用(二)

初识安卓JNI开发,ndk-build+Android.mk+Application.mk实现JNI的调用(一)
前一篇文章讲解到使用Android.mk和Aplication.mk完成JNI的C端的调用,本篇文章用另一种方式,使用Cmake构建jni项目,AS 2.2之后工具中增加了对CMake的支持,官方也推荐用CMake+CMakeLists.txt的方式,代替ndk-build+Android.mk+Application.mk的方式去构建JNI项目。

本篇文章基于Android Studio2.2以上版本进行开发讲解,本篇文章使用的版本为Android Studio3.1.0。

Cmake构建项目实现JNI的调用

1 首先我们需要构建c/c++支持的项目:

image.png

这里我们选择了Native C++进行了创建项目,代表我们的项目支持针对Native的调用。

image.png

同时可以看到我们的项目结构,相对在main目录下增加了cpp这个目录,目录中包含CMakeLists.txt和native-lib.cpp文件。在这里我们 将会主要对这两个文件进行相关配置

2 查看native-lib.cpp文件:

#include 
#include 

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

这里的native-lib.cpp为即将被编译生产动态库的cpp文件 ,这里实为创建项目时候为我们生成的默认文件,根据Java_com_example_jnitest_MainActivity_stringFromJNI可以看到加载文件以及调用方法应该在MainActivity中:

package com.example.jnitest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

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 = 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();
}

2 查看CMakeLists.txt并进行相关配置:

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# 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).
        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})

cmake_minimum_required(VERSION 3.4.1) :编译本地库时我们需要的最小的cmake版本

add_library :相当于Android.mk文件, native-lib 设置生成本地库的名字;SHARED 生成库的类型;native-lib.cpp 需要的cpp文件路径,这里和CMakeLists.txt在同一个目录下所以直接进行引用。否则应用绝对路径 src/main/cpp/native-lib.cpp;

find_library:添加一些我们在编译我们的本地库的时候需要依赖的一些库,这里是默认用来打log的库;

target_link_libraries:关联自己生成的库和一些第三方库或者系统库;

使用CMakeLists.txt同样可以指定so库的输出路径,但一定要在add_library之前设置,否则不会生效:

set(CMAKE_LIBRARY_OUTPUT_DIRECTORY 
    ${PROJECT_SOURCE_DIR}/libs/${ANDROID_ABI}) #指定路径
#生成的so库在和CMakeLists.txt同级目录下的libs文件夹下

如果想要配置so库的目标CPU平台,可以在build.gradle中设置:

android {
    ...
    defaultConfig {
        ...
        ndk{
            abiFilters  "arm64-v8a","armeabi-v7a"
        }
    }
    ...
  
}

设置CMakeList.txt的路径:

android {
   ......
   externalNativeBuild {
        cmake {
            path "src/main/cpp/CMakeLists.txt"
            version "3.10.2"
        }
    }
}

在default:


android {
  ...
  defaultConfig {
    ...
    externalNativeBuild {
      cmake {
        // 指定一些编译选项
        cppFlags "-std=c++11 -frtti -fexceptions"
        ...
 
        // 也可以使用下面这种语法向变量传递参数:
        // arguments "-D变量名=参数".
        arguments "-DANDROID_ARM_NEON=TRUE",
        // 使用下面这种语法向变量传递多个参数(参数之间使用空格隔开):
        // arguments "-D变量名=参数1 参数2"
                  "-DANDROID_CPP_FEATURES=rtti exceptions"
 
        // 指定ABI
        abiFilters "armeabi-v7a" , "arm64-v8a"
      }
    }

defaultConfig 可配置CMake下编译的一些语法,CMake的语法规则这里不进行详细讲解。

配置完成之后,运行项目cpp目录下生成了动态so文件:

image.png

同时项目运行完成,可以看到调用动态库的结果输出:

image.png

这里我们通过Android Studio自动创建的demo完成了CMake方式的一些配置工作。

现在我们在cpp目录下面又新建了一个goodBye.cpp的文件。

#include 
#include 

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_jnitest_MainActivity_sayGoodBye(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Bye Bye Little Java";
    return env->NewStringUTF(hello.c_str());
}

新增了goodBye.cpp文件,定义了sayGoodBye方法并返回"Bye Bye Little Java"字符串。我们同时应该把它打入到动态so库当中,于是我们需要修改一下CMakeLists.txt的配置:

FILE(GLOB SRC_LIST_CPP ${PROJECT_SOURCE_DIR}/*.cpp)
FILE(GLOB SRC_LIST_C ${PROJECT_SOURCE_DIR}/*.c)


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_LIST_CPP} ${SRC_LIST_C})

可以看到我们使用的两个FILE相关的语句,PROJECT_SOURCE_DIR表示当前CMakeLists.txt所在的路径,那么这里把此路径下的cpp文件给遍历存入到SRC_LIST_CPP变量中,同理SRC_LIST_C 则为当前路径下遍历的c文件。而add_library则通过两个变量把所有文件加入了进来。此时生成的so库文件就包含了所有的cpp和c文件。

我们运行项目,点击textview:

image.png

此时textview显示调用sayGoodBye方法返回的字符串。表明so库可被正常调用所含所有文件。

假如现在我们又需要把goodBye.cpp单独放入一个so库中呢,在项目中我们就会经常根据不同功能调用打不同的so文件。

接下来我们继续要去修改CMakeList.txt文件:

add_library( # Sets the name of the library.
        hello

        SHARED

        native-lib.cpp)

target_link_libraries( # Specifies the target library.
        hello

        ${log-lib})


add_library( # Sets the name of the library.
        goodBye

        SHARED

        goodBye.cpp)


target_link_libraries( # Specifies the target library.
        goodBye

        ${log-lib})

我们把goodBye.cpp和 native-lib.cpp分开分别生成本地库,分别取名goodBye和hello。

名字既然已经改了,我们同时需要更改加载so库处的代码。

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("hello");
        System.loadLibrary("goodBye");
    }
}
image.png

libs中分别生成了两份so文件,和我们配置期待的结果一致。同时再去点击textview。正常则成功显示返回的字符串。

上面简单使用Android Studio生成的JNI项目,修改CMakeList.txt以及相关文件,帮助我们生产so文件,具体CMake使用同时还有其他许多的语法内容可查找相关文档进行查看 。

你可能感兴趣的:(初识安卓JNI开发,用Cmake实现JNi的调用(二))