1. 程式人生 > >在Android studio 3.2 版專案中使用cmake呼叫C/C++

在Android studio 3.2 版專案中使用cmake呼叫C/C++

本文操作環境:

win10/Android studio 3.2

1.環境配置

    在SDK Tools裡選擇 CMAKE/LLDB/NDK點選OK 安裝這些外掛.

 

2.建立CMakeLists.txt檔案

  在Project 目錄下,右鍵app,點選新建File檔案,命名為CMakeLists.txt

點選OK,建立完畢!

 

3.配置檔案

  在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.
             test_lib #.so庫名 可自定義

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/jni/test_lib.c ) #原始檔所在目錄

# 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.
                       test_lib #.so庫名 可自定義

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )

 

4.建立一個新的java類

在此類中新增程式碼

package com.example.administrator;

public class Test_lib {
    static {
        System.loadLibrary("test_lib");//載入.so庫
    }

    public static native String getStr(String str);//呼叫C/C++介面函式
}

 

5.在main下面建立jni目錄,建立test_lib.c檔案,名字必須與CMakeLists.txt檔案的原始檔所在目錄一致

 

6.右鍵app,點選Link C++ Project with Gradle

 顯示如下,選擇CMakeLists.txt檔案所在路徑,點選ok,等待構建完成.

構建完成後,build.gradle檔案會自動生成一些配置,如下圖:

 

7.回到Test_lib.java檔案,選中getStr()函式,按下Alt+Enter,點選Create function...,如下圖。

  此時會在test_lib.c檔案裡自動生成C/C++函式。接著就可以在.c檔案裡編寫C/C++介面函數了。

然後Make Project成功後,會在如下目錄生成.so檔案.此時.so庫生成成功,可隨時呼叫了!

 

8.在其他java類中呼叫C/C++函式

   在要呼叫的java類中匯入Test_lib包:

在需要呼叫的地方進行呼叫

 到此處就大功告成了!

初次使用CMake會覺得很繁瑣,但是比傳統的jni呼叫方式要方便很多,多用幾次就會順手了。

 

恕本人水平有限,如有錯誤還請不吝指出!

本文為作者原創,如需轉載請註明出處!