一、流程概述:
1)创建一个文件夹用于存放C/C++代码,一般命名为jni或者cpp。
2)在文件夹中创建CMakeList.txt文件,这个文件是cMake的配置文件。
3)在文件夹中创建第一个C++文件。
4)在CMakeList.txt 文件中配置刚才创建的C++文件。
5)在build.gradle中配置CMake的配置文件(CMakeLists.txt)。
6)在项目的java代码中加载库文件,使用java调用库函数。
二、创建一个文件夹,文件夹名自定义,一般创建在src目录下,名字一般为jni或者cpp。
三、在文件夹下创建CMake的配置文件CMakeList.txt,或者app下创建(Android默认是在这儿),由于之后的配置需要使用相对路径。
cmake_minimum_required(VERSION3.4.1)
add_library(# Sets the name of the library.
#这里只是当前条配置的一个符号,库的文件名,在java中加载就是使用这个名字
native-lib
# Sets the library as a shared library.
#这里代表生成动态链接库,一般不需要改动
SHARED
# Provides a relative path to your source file(s).
#这个是之后需要创建的第一个cpp文件,这里使用的是相对路径名,是相对当前配置文件路径
#如果你之后创建的CPP文件名不同需要修改这一项,改成你创建的文件名。
native-lib.cpp)
#从指定文件夹加载库文件,无需修改
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)
#将其他库链接成一个库方便加载,这个也无需修改
target_link_libraries(# Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib})
四、文件夹中创建cpp文件。
五、按照第三步中配置文件中的提示将你创建的cpp文件配置到对应位置。
六、在build.gradle中添加配置文件。
方法一:点击对应的文件夹右键,选择link C++ Project with Gradle
方法二:在build.gradle中添加配置
android{
externalNativeBuild{
cmake{
//这里文件夹路径根据自己创建的文件夹修改
pathfile('src/main/cpp/CMakeLists.txt')
}
}
}
七、在java中加载链接库
//1)加载库函数
//2)创建调用C++的函数
// 1、函数需要使用native修饰
// 2、函数没有函数体
// 3、如果之前的配置正确这里直接使用alt+enter就可以自动在创建的
// 第一个CPP文件中自动创建对应的函数
package com.example.bohaiservicedome.utils;
public class BchJni {
static {
System.loadLibrary("bchjni");
}
public static native boolean isDecode(int[] secret,int data_count,int ecc_count,int secret_count,int poly);
public static native char[] decode(int[] secret,int data_count,int ecc_count,int secret_count,int poly,int m);
public static native char[] encode(char[] message,int poly);
}