Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to pass float[][] to C++ via JNI

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

like image 241
Haris Hasan Avatar asked Jul 19 '11 18:07

Haris Hasan


2 Answers

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.

like image 91
zacheusz Avatar answered Sep 19 '22 05:09

zacheusz


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);
like image 30
Arpan Sarkar Avatar answered Sep 22 '22 05:09

Arpan Sarkar