AndroidStudio中NDK基礎實踐

前言

轉載出處:基礎配置請看這

自己懶得從頭介紹,看了那麼多博客覺得這位大哥寫的最明白最清楚,附上鍊接,供大家參考。

CMake

推薦使用CMake而不是傳統ndk-build的方式,既然都用新的,自然有它的道理,簡單方便。
有很多人在配置CMakeLists.txt時編譯不通過,是自己的問題嗎?當然,難不成還是它的問題嗎?

這裏給一個範例

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

# 解決shared library text segment is not shareable問題
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wall -v -Wl,--no-warn-shared-textrel")

#引用第三方在jni中使用log,如不使用,可以刪除。
IF (${CMAKE_HOST_SYSTEM_NAME} MATCHES "Windows")
    ADD_DEFINITIONS(-DWindows)
ELSE (${CMAKE_HOST_SYSTEM_NAME} MATCHES "Linux")
    ADD_DEFINITIONS(-DLinux)
ENDIF ()

link_directories(#將頭文件所在目錄告訴編譯器
        ${CMAKE_SOURCE_DIR}/includes)
#指定項目名
project(JniUtil)
# Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.6.0)

# 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.
             JniUtil
             # Sets the library as a shared library.
             SHARED
             # Provides a relative path to your source file(s).
            ${CMAKE_SOURCE_DIR}/JniUtil.cpp
        )
add_library(defence-native
        STATIC
        IMPORTED )  #添加預編譯靜態庫,只需要告訴CMAKE導入項目即可,defence-native爲引入的另一個項目名,上下要保持一致
set_target_properties(defence-native
        PROPERTIES IMPORTED_LOCATION
        ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}/libdefence-native.a)#這裏寫入地址,地址的原地址是從當前文件的父文件夾開始,使用多個ABI是因爲編譯到不同環境需要不同的.a文件

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

# 3.添加並設置靜態庫連接,預構建庫與本地庫相關聯:
target_link_libraries( # Specifies the target library.
                        JniUtil
                        defence-native
                        #z
                        jnigraphics
                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )#這裏只引用了自己所寫的JNI項目和一個靜態文件,編譯成一個so庫

在build.gradle文件中進行配置的時候需要注意

		externalNativeBuild {
            cmake {
                cppFlags "-frtti -fexceptions -fPIC"
                abiFilters  "x86" ,"armeabi-v7a", "arm64-v8a"
            }
        }
        ndk{
            moduleName "JniUtil"
            abiFilters "x86_64", "x86" ,"armeabi-v7a", "arm64-v8a"
        }

cmake下是會編譯輸出的目標ABI;
ndk下是你的項目名以及想要生成的ABI;
記住下面的ndk中的abiFilters要覆蓋cmake中的全部。

示例

截取了一個簡單的方法,傳入字符串調用so庫中的方法。

public class JniUtil {
    static {
        System.loadLibrary("JniUtil");
    }

    public static native void initialize(String string, String logPath);
}
extern "C"
JNIEXPORT void JNICALL Java_com_kxqin_livingrecognitiondemo_JniUtil_initialize
        (JNIEnv* env, jclass jclazz ,jstring jstring1, jstring logPath){
    //獲取字符串指針,必須使用指針,不能使用char strContent[],因爲GetStringUTFChars()返回值爲const char *;
    const char *str = env->GetStringUTFChars(jstring1, JNI_FALSE);
    const char *path = env->GetStringUTFChars(logPath, JNI_FALSE);
    std::string log = path;
    std::string string = str;
    //頭文件中的方法
    defence_native_initialize(string, log);
    //LOGD("initialize is success");
}

更多的用法請關注jni的知識。

然後直接JniUtil.initialize(String1,String2)就可以調用到cpp中的方法了。

調試

基本上都會出大大小小的錯誤,有時候編譯通過但是調用jni中的方法就報錯,
試試在Terminal中輸入

adb logcat | ndk-stack -sym app\build\intermediates\cmake\debug\obj${ABI}

將${ABI}換爲你的ABI,正常情況下在模擬器上使用就是x86,真機就是armabi-v7a或arm64-v8a,
或許能幫你解決不少麻煩。

後話

這裏面的門道很多,我也只是在項目中遇到使用記錄了一下,簡單使用不成問題,深入瞭解可就難爲我了。
其中需要注意的是,

  • jni中儘量少進行字符串操作,儘量移到java中進行,因爲C++對於這一塊着實比java麻煩很多。
  • 提供庫方法的人員一般會返回某個類,這可如何是好?那就更簡單了,自定義一個接收類,映射到java中,比解析它的類要容易很多。
	jclass jcalssResultInfo = env->FindClass("com/***/***demo/ResultBean");
    jmethodID jidResult = env->GetMethodID(jcalssResultInfo, "<init>", "(II[ILjava/lang/String;[I)V");
	...
	jobject resultBean = env->NewObject(jcalssResultInfo, jidResult, resultInt, result.reason, faceArray, env->NewStringUTF(result.msg.data()) ,boxArray);
    return resultBean;

以上變量名稱未替換,僅提供展示效果。

簡單記錄一下,以便自己再需要的時候忘記了如何使用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章