java层和native层进行字符串的交互处理
目标:
java层传递String类型的path路径到native层,path值为"/mnt/sdcard/child.txt";
native层获取String类型path,并转换为char类型指针char* file_path;
通过file_path,如果没有该文件,就创建该文件,并写入"I am a child" 字符串;
具体步骤:
1.在Android工程的MainActivity中添加native方法申明:
public static native void updateFile(String path);
2.通过javah命令生成NDK头文件com_child_hellondk_MainActivity.h
3.在hello.c文件中,实现头文件中的方法JNIEXPORT void JNICALL Java_com_child_hellondk_MainActivity_updateFile(JNIEnv *env, jclass jclass, jstring path)
实现代码如下:
JNIEXPORT void JNICALL Java_com_child_hellondk_MainActivity_updateFile
(JNIEnv *env, jclass jclass, jstring path){
//生成native的char类型指针
const char* file_path = (*env)->GetStringUTFChars(env, path, NULL);
if(file_path != NULL){
LOGV("From c file_path %s", file_path);
}
//打开文件
FILE* file = fopen(file_path, "a+");
if(file != NULL){
LOGV("From c open file success");
}
//写入文件
char data[] = "I am a child";
int count = fwrite(data, strlen(data), 1, file);
if(count > 0){
LOGV("Frome c write file success");
}
//关闭文件
if(file != NULL){
fclose(file);
}
//释放资源
(*env)->ReleaseStringUTFChars(env, path, file_path);
}
4.在MainActivity的OnCreate()方法中调用updateFile(String path)方法,即为调用native层方法;
5.运行程序,在LogCat中打印相应的Log,在/mnt/sdcard/下生成child.txt文件,该文件中有字符串"I am a child".