如何将本机库加载到本机android代码中? (AndroidStudio) [英] How to load native library into native android code? (AndroidStudio)
问题描述
我在C文件夹中有一个名为 mylib 的库 jniLibs/your_architecture/mylib.so
I have a library in C called mylib in the folder jniLibs/your_architecture/mylib.so
在Java中,要加载库,只需在源代码中键入该代码即可:
In Java, to load the library, you just have to type that code in your source:
static {
System.loadLibrary("mylib");
}
但是如何在本机C代码中加载库(在Android Studio中)? 我补充说该库不使用JNI约定,它是一个普通的共享库.
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.
推荐答案
如果这可以帮助某人,那么如何在本机代码c/c ++中加载库:
If this can help someone, here how to load a library in native code c/c++ :
1-以避免java.lang.UnsatisfiedLinkError: dlopen failed:
将此添加到build.gradle到android
块中:
1 - to avoid java.lang.UnsatisfiedLinkError: dlopen failed:
add this to the build.gradle into android
block :
sourceSets {
main {
jniLibs.srcDirs = ['src/main/jniLibs']
}
}
假设您的lib文件位于
Assuming that your lib files are in
src/main/jniLibs/{Architecture}/
src/main/jniLibs/{Architecture}/
(取决于您的jniLibs
文件夹在哪里,在我的情况下,它位于app/src/main/
,但大多数时候在app/
中)
( 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-在您的CMakeList中,通过添加以下块将您的库添加为 SHARED 和 IMPORTED :
2 - In your CMakeList, add you library as SHARED and IMPORTED by adding the following block :
add_library(mylib SHARED
IMPORTED
)
3-通过添加以下代码段,添加目标属性以找到您的lib mylib.so :
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
)
我们在此处后退(/../),因为我们认为CMakeLists.txt位于
We back forward (/../) here because we concidere that CMakeLists.txt is in
src/main/cpp/
src/main/cpp/
否则,大多数时间是在app/
文件夹中,在这种情况下,我们不需要后退.
Otherwise, the most time it is in app/
folder, in this case, we don't need to back forward.
所以我们必须先回到 main/,然后再进入 jniLibs/
So we have to back to main/ before going into jniLibs/
4-将您的lib mylib 添加到目标链接库:
4 - Add you lib mylib to your target link libraries :
target_link_libraries(native-library-jni
..
..
mylib
..
..
)
5-最后,要调用lib mylib.so 中的方法,您必须创建/复制粘贴包含这些方法签名的标头,并将其包含在源文件中:
#include "mylib.h"
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"
您现在可以调用方法[namespace::]method(args...)
其他链接: