//kotlin层
external fun listFiles(filePath:String): String
//native层
#include <jni.h>
#include <string>
#include <dirent.h>
#include <android/log.h>
#ifndef LOG_TAG
#define LOG_TAG "HELLO_JNI"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG ,__VA_ARGS__) // 定义LOGD类型
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG ,__VA_ARGS__) // 定义LOGI类型
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG_TAG ,__VA_ARGS__) // 定义LOGW类型
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG ,__VA_ARGS__) // 定义LOGE类型
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,LOG_TAG ,__VA_ARGS__) // 定义LOGF类型
#endif
extern "C"
JNIEXPORT jstring JNICALL
Java_com_suyf_ndkdev_MainActivity_listFiles(JNIEnv *env, jobject thiz, jstring file_path) {
const char *path = env->GetStringUTFChars(file_path, 0);
DIR *dirPtr = opendir(path);
struct dirent *ptr;
char base[1000];
if (dirPtr == NULL) {
LOGE("opendir fail.....................");
exit(-1);
}
while ((ptr = readdir(dirPtr)) != NULL) {
if (strcmp(ptr->d_name, ".") == 0 ||
strcmp(ptr->d_name, "..") == 0) ///current dir OR parrent dir
continue;
else if (ptr->d_type == 8) ///file
LOGE("d_name:%s/%s
", path, ptr->d_name);
else if (ptr->d_type == 10) ///link file
printf("d_name:%s/%s
", path, ptr->d_name);
else if (ptr->d_type == 4) { ///dir
memset(base, ' ', sizeof(base));
strcpy(base, path);
strcat(base,"/");
strcat(base,ptr->d_name);
LOGE("d_dir:%s/%s
", path, ptr->d_name);
jstring newDir = env->NewStringUTF(base);
Java_com_suyf_ndkdev_MainActivity_listFiles(env,thiz,newDir);
}
}
closedir(dirPtr);
return file_path;
}
错误记录:
Fatal signal 5 (SIGTRAP) code 1 (TRAP_BRKPT)
native层函数缺少return返回值