且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-31 10:50:38

(我假设.so文件是使用Android NDK为Android构建的。如果不是,则为将无法正常工作,您将需要使用Android NDK重建.so文件的源代码)。

(I'm assuming that the .so file is built for Android using the Android NDK. If not, this isn't going to work and you'll need the source to rebuild the .so file using the Android NDK)

假设您有一个名为native-lib的库是为ARMv7A架构构建的,您已将其放在app / prebuilt_libs / armeabi-v7a /中。

Let's say that you've got a library named native-lib that was built for the ARMv7A architecture, and you've placed it in app/prebuilt_libs/armeabi-v7a/.

app / build.gradle:

app/build.gradle:

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

app / CMakeLists.txt

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:

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

For example, if the native library has a function JNIEXPORT jstring JNICALL Java_com_example_bar_MyClass_myNativeFunction, then the Java class would have to be named MyClass and be in the package com.example.bar.

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

您需要为库提供头文件( *。h )。如果没有,则必须弄清楚如何写一个。

You'll need a header file (*.h) for the library. If you don't have one you'll have to figure out yourself how to write one.

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

Then add this in your CMakeLists.txt:

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

对于使用libnative-lib.so的其他本机库:

And for the other native library that uses libnative-lib.so:

target_link_libraries(other_native_lib lib_native)