In my Java code I have a 2D float array float[x][4] floatArray
. Here x
can be between 1 and 25. I have to pass this 2D float array to a C++
method via JNI
. My JNI
method is
jboolean MyJNIMethod(JNIEnv * env, jobject obj, jobjectArray myArray)
{
//how to convert this myArray to something that can be safely passed to C++ method below
}
Inside MyJNIMethod
I have to call a C++
method and pass 2D float array taken from Java to this method
bool MyCplusPlusMethod(float coordinates[][4])
{
}
I am having a hard time in properly converting jobject to float[][] due to lack of native development knowledge. Can anyone tell me the simplest and safest possible way? Thanks
Something like this should work:
jboolean MyJNIMethod(JNIEnv * env, jobject obj, jobjectArray myArray)
{
int len1 = env -> GetArrayLength(myArray);
jfloatArray dim= (jfloatArray)env->GetObjectArrayElement(myArray, 0);
int len2 = env -> GetArrayLength(dim);
float **localArray;
// allocate localArray using len1
localArray = new float*[len1];
for(int i=0; i<len1; ++i){
jfloatArray oneDim= (jfloatArray)env->GetObjectArrayElement(myArray, i);
jfloat *element=env->GetFloatArrayElements(oneDim, 0);
//allocate localArray[i] using len2
localArray[i] = new float[len2];
for(int j=0; j<len2; ++j) {
localArray[i][j]= element[j];
}
}
//TODO play with localArray, don't forget to release memory ;)
}
Note that this is outline. It won't compile ;) (I wrote it in this overstacks' editor)
In your class you should declare native method:
public native void myJNIMethod(float[][] m);
and in your c code corresponding:
JNIEXPORT jboolean JNICALL Java_ClassName_methodName (JNIEnv *, jobject, jobjectArray);
Here is JNI array operations documentation.
For releasing the allocated memory you can do something like this:
static void releaseMatrixArray(JNIEnv *env, jobjectArray matrix) {
int size = (*env)->GetArrayLength(env, matrix);
for (int i = 0; i < size; i++) {
jfloatArray oneDim = (jfloatArray) (*env)->GetObjectArrayElement(env, matrix, i);
jfloat *elements = (*env)->GetFloatArrayElements(env, oneDim, 0);
(*env)->ReleaseFloatArrayElements(env, oneDim, elements, 0);
(*env)->DeleteLocalRef(env, oneDim);
}
}
release local Array reference:
free(localArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With