Android NDKAndroid 学习笔记Android开发

添加 C/C++ 代码

2018-04-27  本文已影响31人  mlya

Add C and C++ Code

如何在 Android 中使用 C 或者 C++ 代码.

我最近在做一个视频直播的项目, 需要将视频推流到服务器, 网上现在有很多已经做好的 Android 推流器, 但是我想自己使用 FFMpeg 来自己实现一个, 同时学习一下 Android 使用 C 或者 C++ 的方式.

HelloCPP

我们先看一个来自 C 的 Hello World!

新建项目

在创建项目时, 选择 Include C++ support.

15247093656280

这将为我们的项目添加一些必要的 C++ 支持的文件, 下面我们将仔细分析这些文件.

文件结构

C++ 和 C 支持的 Android Studio 工程的目录结构有些不同, 我们分 Android 视图和 Project 视图来分别看一下

Android 视图
15247102352563-w453

Android 视图的项目结构如上图所示.

从大的角度来看, 除了 app module 和 Gradle Scripts 之外, 多出来了一个是 External Build Files 这个目录. External Build Files 包含了一个 CMakeLists.txt 文件, Android Studio 默认采用 CMake 来编译 C++ 和 C 源码, 这个文件是 CMake 的配置文件.

在 app module 下, 多出了一个 cpp 的目录, 里面包含了一个 native-lib.cpp 的文件, 这是 Android Studio 生成的 C++ 示例文件.

Project 视图

那么真实的物理目录结构是什么样的呢? 我们可以来看一下:

Screen Shot 2018-04-26 at 14.28.18

项链书多出了上面的三个文件:

示例代码

下面我们就来看一看示例代码中 Android 是如何引入 C++ 支持的.

首先来看我们的 Java 代码:

package com.dcr.hellomycpp;

import android.support.v7.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 = (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();
}

其中主要有两处变化, 我们现在关注后面的一处:

public native String stringFromJNI();

了解过 JNI 的应该知道, 这一句是定义了 Java 的 JNI 接口, 使用了 native 关键字, 来声明 Native 调用, 这个方法的实现将在 c/c++ 中完成.

接下来我们可以看一下这个 native 方法是如何实现的, native-lib.cpp 的实现如下:

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

extern "C" JNIEXPORT jstring

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

这段代码中的每个字段的具体含义, 我们在后面详细解释, 这里我们只要理解, 这就是 Java 中的 native 方法 stringFromJNI 的 C++ 实现.

CMakeLists.txt

我们只在源代码中引入 C++ 是还不够的, 我们的编译器还不能够正确的编译整个项目, 还需要我们前面提到过的 CMakeLists.txt 文件.

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

这段代码中有三个主要部分: add_library, find_librarytarget_link_libraries.

add_library
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 )

add_library 传入三个参数:

find_library

find_library 用来添加一些编译本地库时需要依赖的一些库, 由于 CMake 已经知道系统库的路径 所以我们这里只是指定使用 log 库, 然后起了一个别名 log-lib 方便使用, log 库是 NDK 为我们提供的调试时打印 log 日志的库.

target_link_libraries

关联我们的库和第三方库或者系统库, 这里我们把我们的库和 log 库关联起来.

build.gradle

我们还需要在 gradel 中引入相关配置. 使用 CMake 配置需要在 Gradle 的两处引入 externalNativeBuild 语句块

  1. 在 android 语句块中, 引入 externalNativeBuild, 用来指定 CMakeLists.txt 的位置.

    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
    
  2. 在 defaultConfig 中引入 externalNativeBuild, 用来指定额外的参数.

    externalNativeBuild {
            cmake {
                cppFlags ""
                abiFilters "armeabi"
            }
    }
    

运行结果

OK, 现在, 我们已经分析了整个项目的结构和配置, 现在让我们运行一下, 看一下结果吧:

device-2018-04-27-101830

如果我们分析 apk 文件我们会看到 apk 中包含了 .so 动态链接库.

Screen Shot 2018-04-27 at 10.21.22
上一篇下一篇

猜你喜欢

热点阅读