链接第三方动态库
下面模拟链接第三方动态库的过程
一、编译一个动态库
1.1 在CMakeLists.txt中配置(其实也是androidStudio新建一个包含c++的默认配置)
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/cpp/add.c )
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log )
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib} )
1.2 在add.c中添加一个测试方法
#define TAG "399"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG,__VA_ARGS__)
int add(int a, int b){
LOGE("c开始计算");
return a+b;
}
1.3 点击Rebuild Project,等待编译结束,切到到project项目下的app/intermediates/cmake/debug/obj,如下图:
把所有平台的so库复制下来添加到测试工程的lib目录下,再在app的bulid.gradle的android节点下添加:
sourceSets.main {
jniLibs.srcDirs = ['libs']
jni.srcDirs = []
}
到这里需要模拟依赖的第三方库就做好了,如果有这直接copy到lib中,可以跳过此步骤,直接看第二步
二、配置CMakeLists.txt,链接到这个第三方库
在CMakeLists.txt中添加和修改
#需添加
#设置so库路径,设置my_lib_path为相对CMakeLists.txt路径下的libs目录
set(my_lib_path ${CMAKE_SOURCE_DIR}/libs)
#将第三方库作为动态库引用,native-lib其实就是刚刚编译的so库,全名为libnative-lib.so
add_library( native-lib
SHARED
IMPORTED )
#需添加
#指名第三方库的绝对路径ANDROID_ABI为build.gradle中配置要编译的平台
set_target_properties( native-lib
PROPERTIES IMPORTED_LOCATION
${my_lib_path}/${ANDROID_ABI}/libnative-lib.so )
#需修改
#链接动态库
target_link_libraries( # Specifies the target library.
filelib//自己开发用的
native-lib//第三方动态库
# Links the target library to the log library
# included in the NDK.
${log-lib} )
#filelib为自己需要编译的.so库名字
add_library( # Sets the name of the library.
filelib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/cpp/hello.c )
#不修改
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log )
三、开始写自己的代码测试
3.1 新建头文件add.h 如下:声明add方法:
#ifndef NDKTEST2_ADD_H
#define NDKTEST2_ADD_H
extern int add(int a,int b);
#endif //NDKTEST2_ADD_H
3.2
java中编写native 方法
public native int add(int a,int b);
c中调用第三方库
JNIEXPORT jint JNICALL Java_com_cool_ndktest2_MainActivity_add
(JNIEnv * env, jobject jobj,jint jint1,jint jint2){
int result = add(jint1,jint2);
return result;
}
3.3 java中使用
3.3.1 加载动态库
static {
System.loadLibrary("native-lib");
System.loadLibrary("filelib");
}
3.3.2 java调用及运行结果
java调用:
int sum = add(100,100);
Log.e("399","sum: " + sum);
运行结果:
E/399: c中开始计算
E/399: sum: 200