1、在app\libs中增加对应的so
2、在build.gradle中增加
externalNativeBuild {
cmake {
path file('src/main/cpp/CMakeLists.txt')
}
}
sourceSets {
main {
jniLibs.srcDirs = ["libs"]
}
}
3、CMakeList.txt文件
cmake_minimum_required(VERSION 3.22.1)
project("test")
add_library(test SHARED
layer3/Layer3.cpp
)
find_library( log-lib log )
target_link_libraries(test ${log-lib})
include_directories(./include)
4、在include下包含对应的头文件
5、Layer3.cpp
#include <dlfcn.h>
#include <pthread.h>
#include <android/log.h>
#include <jni.h>
#define SO_PATH "libother.so"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,"lmy",__VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,"lmy",__VA_ARGS__)
typedef ULONG (*Test_f)(const char *name);
typedef struct {
Test_f TestFn;
} ApiTable;
static ApiTable g_ApiTable;
static void *g_libHandle = NULL;
static pthread_mutex_t g_libHandleLock = PTHREAD_MUTEX_INITIALIZER;
static ULONG GetBasicApiSymbol(ApiTable *ApiTable) {
ApiTable->TestFn = (Test_f) (dlsym(g_libHandle, "TEST"));
if (ApiTable->TestFn == NULL) {
LOGE("get symbol TEST failed\n");
return 0xFFFF0000;
}
return 0;
}
static ULONG GetApiSymbol() {
ApiTable apiTable = {0};
(void)pthread_mutex_lock(&g_libHandleLock);
g_libHandle = dlopen(SO_PATH, RTLD_LAZY);
if (g_libHandle == NULL) {
(void) pthread_mutex_unlock(&g_libHandleLock);
return 1;
}
if (GetBasicApiSymbol(&apiTable ) != 0) {
LOGE("get symbol failed\n");
goto ERROR;
}
g_ApiTable = apiTable ;
(void) pthread_mutex_unlock(&g_libHandleLock);
return 0;
ERROR:
dlclose(g_libHandle);
g_libHandle = NULL;
(void) pthread_mutex_unlock(&g_libHandleLock);
return 0xFFFF0000;
}
extern "C" JNIEXPORT long JNICALL
Java_com_xxx_Native_init(JNIEnv
*env,
jobject instance){
GetApiSymbol();
ULONG re =g_ApiTable.TestFn("hello world");
LOGI("0x%x",re);
return re;
}