JNI开发Android开发经验谈Android开发

NDK 基本知识点

2017-11-25  本文已影响49人  未见哥哥

NDK

为什么要使用到 NDK 呢?

NDK 的优缺点

优点:

  1. 运行效率高
  2. 利于充分发挥软硬件优势
  3. 利于代码复用
  4. 降低版本控制成本
  5. 降低开发成本

缺点:

  1. 开发难度较高
  2. 调试难度较高(以库的形式存在)
  3. 增加开发团队规模

怎么使用 NDK

关注两点:

  1. 如何进行 c/c++ 代码的编译?
  2. 如何将编译后的 so 库打包到 apk 中?

AS2.2 以上版本默认支持在 gradle 中使用 NDK 将 c/c++ code 编译成一个本地 so 库中然后打包到 APK 中。而在 AS 中默认编译 native 代码的工具就是 CMake,不过 AS 也是支持 ndk-build 的方式去编译 native 代码。官网推荐如果是新建的项目,优先使用 CMake

准备工作

NDK 及其工具的下载

使用步骤

#include <jni.h>
#include <string>

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

截图

CMake 的介绍

CMake是一个跨平台的安装(编译)工具,可以用简单的语句来描述所有平台的安装(编译过程)。他能够输出各种各样的makefile或者project文件,能测试编译器所支持的C++特性,类似UNIX下的automake。

CMaker 使用 :CMake的所有的语句都写在一个叫:CMakeLists.txt的文件中。当CMakeLists.txt文件确定后,可以用ccmake命令对相关 的变量值进行配置。这个命令必须指向CMakeLists.txt所在的目录。配置完成之后,应用cmake命令生成相应的makefile(在Unix like系统下)或者 project文件(指定用window下的相应编程工具编译时)。

  1. 指定 CMake 版本
  2. 指定需要构建的 so 的类型,SHARE 或者 STATIC
  3. 指定需要编译的源文件
# CMake 命令配置构建脚本
# Sets the minimum version of CMake required to build your native library.
# This ensures that a certain set of CMake features is available to
# your build.

cmake_minimum_required(VERSION 3.4.1)

# Specifies a library name, specifies whether the library is STATIC or
# SHARED, and provides relative paths to the source code. You can
# define multiple libraries by adding multiple add_library() commands,
# and CMake builds them for you. When you build your app, Gradle
# automatically packages shared libraries with your APK.

# add_library 可以定义多个
add_library( # Specifies 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 )
             
# 为了让 CMake 在编译期间就可以找到文件。
# Specifies a path to native header files.
include_directories(src/main/cpp/include/)

gradle 构建本地库的过程

运行结果

截图

验证最终 apk 包中有哪些 so 库

Build->Analyzer APK 即可

截图

如何使用别人编译好的 so 库呢?

需要根据不同的cpu架构把函数库在 src/main/jniLibs 目录下

上一篇下一篇

猜你喜欢

热点阅读