How to import and use .so file in NDK project ( An

2019-08-23 04:35发布

I am trying to import and use .so file in android studio NDK project. I have read the documentation of android studio, different blog, and answers on StackOverflow but none is working for me because most of them are outdated ( written or asked 3-4 year ago ). Also unable to follow the documentation.

Please Help!

1条回答
来,给爷笑一个
2楼-- · 2019-08-23 05:02

(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)

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:

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)

If the library is meant to be used from 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();
}

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.


If the library is meant to be used by other native libraries

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.

Then add this in your CMakeLists.txt:

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

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

target_link_libraries(other_native_lib lib_native)
查看更多
登录 后发表回答