1. 程式人生 > >Android NDK開發之引入第三方庫

Android NDK開發之引入第三方庫

在Android開發中我們經常要把一些比較看重安全或者計算效率的東西通過JNI呼叫C/C++程式碼來實現,如果需要實現的功能簡單或者你的C/C++程式碼能力比較強,但是目前還是有很多功能強大的第三方庫的,比如openssl、FFmpeg等,呼叫這些第三方實現顯然比重複造輪子實際的多。

本教程適合將原始的動態庫(.so),即沒有包含JNI方法因而java無法直接呼叫的庫連結到自己的C/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 ) 複製程式碼

連結靜態庫

## 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來區分

${CMAKE_SOURCE_DIR}是CMake 中預定義的常量,指當前工程的 CMake 檔案所在路徑,其他比較有用的常量:

  • CMAKE_CURRENT_SOURCE_DIR : 指當前 CMake 檔案所在的資料夾路徑

  • CMAKE_CURRENT_LIST_FILE : 指當前 CMake 檔案的完整路徑

  • PROJECT_SOURCE_DIR :指當前工程的路徑

最後將所有庫連結起來就行了:

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動態庫和靜態庫的方法。 專案的檔案結構目錄如下:

  • 拷貝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);

}
複製程式碼

結果如下:

遇到的錯誤:

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']
        }
    }
複製程式碼