如何在NDK项目(Android Studio)中导入和使用.so文件



我正在尝试在android studio NDK项目中导入和使用.so文件。我已经阅读了android工作室的文档,不同的博客,以及StackOverflow上的答案,但没有一个对我有用,因为它们大多已经过时了(3-4年前写的或问过(。也无法遵循文档。

请帮忙!

假设您有一个名为native lib的库,它是为ARMv7A体系结构构建的,并将其放置在app/prebuilt_libs/armeabi-v7a/中。

app/build.gradle:

android {
...
defaultConfig {
...
ndk {
abiFilters "armeabi-v7a"
}
}
...
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
sourceSets.main {
jniLibs.srcDirs = ['prebuilt_libs']
}

app/CMakeLists.txt

cmake_minimum_required(VERSION 3.4.1)
add_library(lib_native SHARED IMPORTED)
set_target_properties(lib_native PROPERTIES IMPORTED_LOCATION ${CMAKE_SOURCE_DIR}/prebuilt_libs/${ANDROID_ABI}/libnative-lib.so)

如果要从Java使用库

CallNative.java:

package com.example.foo;  // !! This must match the package name that was used when naming the functions in the native code !!

public class CallNative {  // This must match the class name that was used when naming the functions in the native code !!
static {
System.loadLibrary("native-lib");
}
public native String myNativeFunction();
}

例如,如果本机库有一个函数JNIEXPORT jstring JNICALL Java_com_example_bar_MyClass_myNativeFunction,那么Java类必须命名为MyClass,并且位于包com.example.bar中。


如果该库打算由其他本机库使用

您需要库的头文件(*.h(。如果你没有,你就得自己想办法写。

然后将其添加到您的CMakeLists.txt中:

set_target_properties(lib_native PROPERTIES INCLUDE_DIRECTORIES directory/of/header/file)

对于另一个使用libnative-lib.so的本地库:

target_link_libraries(other_native_lib lib_native)

最新更新