How to load native library into native android code? (AndroidStudio)

纵然是瞬间 提交于 2019-12-07 23:33:16

问题


I have a library in C called mylib in the folder jniLibs/your_architecture/mylib.so

In Java, to load the library, you just have to type that code in your source:

static {
  System.loadLibrary("mylib");
}

But how can you load the library in a native C code (in Android Studio) ? I add that the library don't use the JNI conventions, it's a normal shared library.


回答1:


If this can help someone, here how to load a library in native code c/c++ :

1 - to avoid java.lang.UnsatisfiedLinkError: dlopen failed: add this to the build.gradle into android block :

sourceSets {
    main {
        jniLibs.srcDirs = ['src/main/jniLibs']
    }
}

Assuming that your lib files are in

src/main/jniLibs/{Architecture}/

( depending where is your jniLibs folder, in my case it is located at app/src/main/ but the most time it is in app/)


2 - In your CMakeList, add you library as SHARED and IMPORTED by adding the following block :

add_library(mylib SHARED
            IMPORTED
            )

3 - Add target properties to locate you lib mylib.so by adding the following block :

set_target_properties( mylib PROPERTIES 
IMPORTED_LOCATION 
${PROJECT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/mylib.so
)

We back forward (/../) here because we concidere that CMakeLists.txt is in

src/main/cpp/

Otherwise, the most time it is in app/ folder, in this case, we don't need to back forward.

So we have to back to main/ before going into jniLibs/


4 - Add you lib mylib to your target link libraries :

target_link_libraries(native-library-jni
                      ..
                      ..
                      mylib
                      ..
                      ..
                      )


5 - Finally, to call methods of your lib mylib.so, you have to create/copy-past the header containing these methods signatures and include it in your source file : #include "mylib.h"

You can now call your methods [namespace::]method(args...)


Extra links :

PROJECT_SOURCE_DIR

CMAKE_SOURCE_DIR

Q : Are CMAKE_SOURCE_DIR and PROJECT_SOURCE_DIR the same in CMake?



来源:https://stackoverflow.com/questions/45314478/how-to-load-native-library-into-native-android-code-androidstudio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!