I'm new to jni programming. I'd like to pass a float array from java to jni, allocate sufficient memory dynamically to float array in jni side, store some values in the jfloatArray, and access it in java. I don't want to return the jfloatArray, just modify the input float array passed. I tried the below method but it is not modifying my java float array. How to achieve this?
Java Code:
float[] pointList = null;
outputBitmap = callJNIFunc(pointList, inputBitmap);
JNI Code:
Bitmap callJNIFunc(JNIEnv *env, jfloatArray pointListInPixels, jobject inputBitmap) {
pointListInPixels = (env)->NewFloatArray(pointListSize.M * 2);
env->SetFloatArrayRegion(pointListInPixels, 0, pointListSize.M * 2, pointFloats);
}
I read from pass data between Java and C that this can be achieved by passing a Custom Object. However, I'm not quite sure how to do this from jni for a java Object containing float array like this
public class CustomObject{
public float[] points;
public float[] getPoints() {
return points;
}
public void setPoints(float[] points) {
this.points = points;
}
}
Look at the first line of your JNI function.
Initially,
pointListInPixels
represents the address of a Java object - thefloat[] pointList
in your java code.In the very next line, you assign it to
(env)->NewFloatArray
, which means thatpointListInPixels
no longer points to yourfloat[] pointList
in Java, but to a new array. As a result, your call toSetFloatArrayRegion
has no effect. It modifies an array in Java, sure, but it doesn't modify the array you want it to modify.The correct method of doing this is to make your JNI function return a
jFloatArray
, converting your java code to:and your JNI code to:
Method signatures should be changed as required.