jni中应用层和native层是怎样交互呢?关于jni的用法我们可以参照http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/jniTOC.html。下面用一个小例子来说明,java和c++的交互,主要讲三部分,对字符串、数组的处理和c++回调java函数。
字符串的处理
在Java类中声明native接口
//交互处理之字符串的处理
public static native void modifyFile(String path);
在jni中.cpp文件中添加相应的c++实现:
JNIEXPORT void JNICALL Java_com_vince_jnidemo_MainActivity_modifyFile
(JNIEnv *env, jclass jclas, jstring path){
const char* file_path = env->GetStringUTFChars(path,NULL);//进行类型转换,jstring->char*
if(file_path != NULL){
LOGV("file_path in c %s",file_path);
}
//打开文件
FILE* file = fopen(file_path,"a+");
if(file != NULL){
LOGV("open file success in c");
}
//写入文件
char data[]="hello jni";
int count = fwrite(data,strlen(data),1,file);
if(count > 0){
LOGV("write file success in c");
}
//关闭文件
if(file != NULL){
fclose(file);
}
//释放资源
env->ReleaseStringUTFChars(path,file_path);
}
数组的处理
native的接口实现中对于数组有两种处理方案:
1、第一种方式是生成native层的数组拷贝
2、第二种方式是直接调用数组指针进行操作
在Java类中声明native接口
//交互处理之数组处理
public static native int[] modifyIntArray(int[] data);
在jni中.cpp文件中添加相应的c++实现:
JNIEXPORT jintArray JNICALL Java_com_vince_jnidemo_MainActivity_modifyIntArray
(JNIEnv *env, jclass jclas, jintArray array){
//通过生成native层的数组拷贝操作数组
jint nativeArray[5];
env->GetIntArrayRegion(array, 0 , 5, nativeArray);
int j;
for(j = 0; j < 5; j++){
nativeArray[j] += 5;
LOGV("nativeArray---> %d", nativeArray[j]);
}
env->SetIntArrayRegion(array, 0, 5, nativeArray);
/*
//通过生成native层的数组拷贝操作数组
jint* data = env->GetIntArrayElements(array,NULL);//生成对应的指针
jsize len = env->GetArrayLength(array);//获取到长度
int j;
for(j = 0; j< len; j++){
data[j] += 3;
LOGV("data from c %d",data[j]);
}
//释放资源
env->ReleaseIntArrayElements(array,data,0);
*/
return array;
}
native回调java函数
在Java类中声明native接口
//交互处理之从native中调用java层函数
public static native void callJavaMethodFromNative();
在jni中.cpp文件中添加相应的c++实现:
JNIEXPORT void JNICALL Java_com_vince_jnidemo_MainActivity_callJavaMethodFromNative
(JNIEnv *env, jclass jclas){
jmethodID java_method = env->GetStaticMethodID(jclas, "printInfo", "()V");
if (java_method == NULL)
{
LOGV("java_method为空");
}
env->CallStaticVoidMethod(jclas,java_method);
}
看了这么你可能会问,这么多函数从哪里查找,我们可以从E:\java\android-ndk-r9d\platforms\android-14\arch-arm\usr\include\jni.h中查看相应的函数。
jniDemo地址: http://download.csdn.net/detail/u012350993/9426813