I have a C function to be used in an Android app that "returns" multiple short (int) pointers and the number of short ints pointed to by each pointer via the parameter list. I want to return all these lists to the calling Java class, so can't use a single return type for the function. It seems that I need to know before hand the size of the list in order to pre-allocate a java short[] with enough memory as follows:

inside java class

short[] fooArr = new short[2];
short[] mooArr = FibLib.testFunc(fooArr);

inside c file

JNIEXPORT jshortArray JNICALL Java_com_funTest_testFunc(JNIEnv *env, jclass clazz, jshortArray retData) {
// retData is the data returned to the caller via the parameter list
// it is declared in the java section and a pointer is created here
jshort outCArray[] = {100, 200};  // some fake data; in reality the size of this list is unknown until runtime 
jshort *cArray = (*env)->GetShortArrayElements(env, retData, NULL);
if (cArray == NULL)
{
    return 0;
}
else
{
    //jini len = (*env)->GetArrayLength(env, array);
    jsize len = (*env)->GetArrayLength(env, retData);
    jint ix;
    for (ix = 0; ix < len; ix++) {
        cArray[ix] = outCArray[ix]; // this will modify retData with the new values when we release
    }
    (*env)->ReleaseShortArrayElements(env, retData, cArray, 0); // mode 0 to copy back the content and free cArray
}

jshortArray outJNIArray = (*env)->NewShortArray(env, 2);  // allocate
//if (NULL == outJNIArray) return -1;
(*env)->SetShortArrayRegion(env, outJNIArray, 0 , 2, outCArray);  // copy
return outJNIArray;
}

If I don't know the size of retData beforehand, how do I pass a "resizeable" fooArr to testFunc?

Related posts

Recent Viewed