Android NDK開發之引入第三方庫

在Android開發中咱們常常要把一些比較看重安全或者計算效率的東西經過JNI調用C/C++代碼來實現,若是須要實現的功能簡單或者你的C/C++代碼能力比較強,可是目前仍是有不少功能強大的第三方庫的,好比openssl、FFmpeg等,調用這些第三方實現顯然比重複造輪子實際的多。html

本教程適合將原始的動態庫(.so),即沒有包含JNI方法於是java沒法直接調用的庫連接到本身的C/C++代碼中,而後提供調用。java

連接系統標準庫

# 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 )
複製代碼

連接靜態庫

## libpng動態庫的設置
add_library( # Sets the name of the library.
        png
        # Sets the library as ashared library.
        STATIC
        # Provides a relative pathto your source file(s).
        IMPORTED)
set_target_properties(
        png
        PROPERTIES IMPORTED_LOCATION
        ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}/libpng.a)
複製代碼

連接動態庫

## 引入libssl動態庫
add_library(ssl SHARED IMPORTED)
set_target_properties(
        ssl
        PROPERTIES IMPORTED_LOCATION
        ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}/libssl.so)
複製代碼

添加連接外部靜態庫和動態庫的流程差很少,用STATICSHARED來區分android

${CMAKE_SOURCE_DIR}是CMake 中預約義的常量,指當前工程的 CMake 文件所在路徑,其餘比較有用的常量:git

  • CMAKE_CURRENT_SOURCE_DIR : 指當前 CMake 文件所在的文件夾路徑github

  • CMAKE_CURRENT_LIST_FILE : 指當前 CMake 文件的完整路徑算法

  • PROJECT_SOURCE_DIR :指當前工程的路徑安全

最後將全部庫連接起來就好了:bash

target_link_libraries( # Specifies the target library.
        native-lib
        png
        openssl
        ssl
        android

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

實戰:引入openssl庫供android使用

openssl是一款強大的加解密庫,提供了RSA、AES、MD5等經常使用的加密算法,網上也有不少編譯openssl動態庫和靜態庫的方法。 項目的文件結構目錄以下:app

  • 拷貝openssl的so文件到lib文件夾下
  • 拷貝openssl的頭文件到cpp的include目錄
  • 編寫cmake文件
# 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)

#配置加載頭文件
include_directories(./src/main/cpp/include)
file(GLOB mian_src "src/main/cpp/*.cpp")
# 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.
        cipher

        # Sets the library as a shared library.
        SHARED

        # Provides a relative path to your source file(s).
        ${mian_src} )

#動態方式加載
add_library(openssl SHARED IMPORTED )
add_library(ssl SHARED IMPORTED )
#引入第三方.so庫
set_target_properties(openssl PROPERTIES IMPORTED_LOCATION ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}/libcrypto.so)
set_target_properties(ssl PROPERTIES IMPORTED_LOCATION ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}/libssl.so)

# 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.
        cipher
        openssl
        ssl
        android

        # Links the target library to the log library
        # included in the NDK.
        ${log-lib} )
複製代碼
  • 編寫代碼調用openssl頭文件裏面提供的方法:
extern "C"
JNIEXPORT jstring JNICALL Java_org_hik_arraytest_MainActivity_md5(JNIEnv *env, jobject instance, jbyteArray src_) {
    Log_d("MD5->信息摘要算法第五版");
    jbyte *src = env->GetByteArrayElements(src_, NULL);
    jsize src_Len = env->GetArrayLength(src_);

    char buff[3] = {'\0'};
    char hex[33] = {'\0'};
    unsigned char digest[MD5_DIGEST_LENGTH];

    MD5_CTX ctx;
    MD5_Init(&ctx);
    Log_d("MD5->進行MD5信息摘要運算");
    MD5_Update(&ctx, src, src_Len);
    MD5_Final(digest, &ctx);

    strcpy(hex, "");
    Log_d("MD5->把哈希值按%%02x格式定向到緩衝區");
    for (int i = 0; i != sizeof(digest); i++) {
        sprintf(buff, "%02x", digest[i]);
        strcat(hex, buff);
    }
    Log_d("MD5->%s", hex);

    Log_d("MD5->從jni釋放數據指針");
    env->ReleaseByteArrayElements(src_, src, 0);

    return env->NewStringUTF(hex);
}
複製代碼
  • java裏調用jni方法
public class MainActivity extends AppCompatActivity {

    String TAG = "my_openssl";
    
    static {
        System.loadLibrary("cipher");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i(TAG, "MD5信息摘要->" + md5("1111".getBytes()).toUpperCase());
    }
    /**
     * MD5編碼
     */
    public native String md5(byte[] src);

}
複製代碼

結果以下:ide

遇到的錯誤:

java.lang.UnsatisfiedLinkError:
dlopen failed: library "/system/lib64/libcrypto.so" needed or dlopened by "/system/lib64/libnativeloader.so" 
is not accessible for the namespace "classloader-namespace"
複製代碼
java.lang.UnsatisfiedLinkError: dlopen failed: library "libcrypto.so" not found
複製代碼

在app的build.gradle中指定第三方so文件目錄,否則生成apk文件的時候不會包含這些so文件。

sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
複製代碼
相關文章
相關標籤/搜索