引用前提说明:
- 需要对应ABI的第三方so库,我这边已我自己编译完成的arm64-v8a的gmssl库为例,拥有libgmssl.so文件
- 需要第三方库提供的暴露so库中的方法的.h文件,一般会提供include文件夹内涵.h文件
- 在Android项目中已经进行了cxx连接,存在cpp目录以及目录下已经有cmakelists.txt文件
引用使用步骤:
-
在项目或者模块的libs文件夹下新建对应ABI的文件夹我这边创建arm64-v8a文件夹并将so库放入其中
-
将include文件夹复制到项目或者模块的src/main/cpp文件夹下
-
在CMakeLists.txt中进行配置,需要添加的配置如下:
#用于将LIB_DIR指向项目或者模块下的libs文件夹中 set(LIB_DIR ${CMAKE_SOURCE_DIR}../../../../libs/arm64-v8a)
-
#添加gmssl库 这边可以替换为你们自己需要添加的第三方so库的名称不包含lib和.so add_library(gmssl SHARED IMPORTED) #设置添加方式为本地添加并将路径指向libgmssl.so set_target_properties(gmssl PROPERTIES IMPORTED_LOCATION ${LIB_DIR}/libgmssl.so)
-
#向当前项目或者模块添加第三方库的include目录,使之后在自己的cpp文件中能引用第三方库 target_include_directories(SIKEncrypt PRIVATE ${CMAKE_SOURCE_DIR}/include)
-
#在项目或者模块中引用gmssl库 target_link_libraries( # Specifies the target library. SIKEncrypt # Links the target library to the log library # included in the NDK. gmssl ${log-lib})
-
下面贴出完整的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.22.1) # Declares and names the project. project("SIKEncrypt") # 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. SIKEncrypt # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). SIKEncrypt.cpp) # Set the path to the directory containing the prebuilt libraries set(LIB_DIR ${CMAKE_SOURCE_DIR}../../../../libs/arm64-v8a) add_library(gmssl SHARED IMPORTED) set_target_properties(gmssl PROPERTIES IMPORTED_LOCATION ${LIB_DIR}/libgmssl.so) target_include_directories(SIKEncrypt PRIVATE ${CMAKE_SOURCE_DIR}/include) # 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. SIKEncrypt # Links the target library to the log library # included in the NDK. gmssl ${log-lib})
到此第三方so库算是添加完成了并可以正常使用了,如果对你有什么帮助的话,麻烦点个赞?感谢!