Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...