Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning jbyteArray from native c in Android

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;

}

How it is done?

like image 607
Raneez Ahmed Avatar asked Apr 30 '12 12:04

Raneez Ahmed


1 Answers

use SetByteArrayRegion

charCnt=fread(data, 1, size, fin);

jbyteArray result=(*env)->NewByteArray(env, size);

(*env)->SetByteArrayRegion(env, result, 0, size, data);



one could also use GetByteArrayElements eg:

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);

see here for more details on SetByteArrayRegion, GetByteArrayElements and ReleaseByteArrayElements.


NB: this question is probably a special case of this question

like image 121
violet313 Avatar answered Oct 11 '22 09:10

violet313