本文介绍了从Android中的本机C返回jbyteArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用本机c从音频文件读取数据到jbyte指针.现在我想将其作为jbyteArray发送到java.
I use native c to read data from an audio file to jbyte pointer. Now i want to send it to java as an jbyteArray.
jbyteArray Java_com_app_audio_player_readData(JNIEnv * env, jobject jobj,jstring readPath)
{
FILE *fin;
const char *inFile= (*env)->GetStringUTFChars(env,readPath,0);
fin = fopen(inFile, "r");
fseek(fin, 0, SEEK_END); // seek to end of file
int size = ftell(fin); // get current file pointer
fseek(fin, 0, SEEK_SET);
jbyte *data=(jbyte *)malloc(size*sizeof(jbyte));
int charCnt = 0;
charCnt=fread(data, 1, size, fin);
jbyteArray result=(*env)->NewByteArray(env, size);
//-- I want to convert data to jbyteArray and return it to java
fclose(fin);
return result;
}
如何完成?
推荐答案
使用SetByteArrayRegion
charCnt=fread(data, 1, size, fin);
jbyteArray result=(*env)->NewByteArray(env, size);
(*env)->SetByteArrayRegion(env, result, 0, size, data);
也可以使用GetByteArrayElements
例如:
jboolean isCopy;
jbyte* rawjBytes = (*env)->GetByteArrayElements(env, result, &isCopy);
//do stuff to raw bytes
memcpy(rawjBytes, data, size*sizeof(jbyte));
(*env)->ReleaseByteArrayElements(env, result, rawjBytes, 0);
请参见此处以获取更多信息SetByteArrayRegion
,GetByteArrayElements
和ReleaseByteArrayElements
的详细信息.
see here for more details on SetByteArrayRegion
, GetByteArrayElements
and ReleaseByteArrayElements
.
注意::这个问题可能是
NB: this question is probably a special case of this question
这篇关于从Android中的本机C返回jbyteArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!