开发者

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开发者_Python百科. 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜