通过 JNI 将 float[][] 传递给 C++ 的最简单方法

2022-01-25 00:00:00 c++ java java-native-interface

在我的 Java 代码中,我有一个 2D 浮点数组 float[x][4] floatArray.这里 x 可以介于 1 和 25 之间.我必须通过 JNI 将这个 2D 浮点数组传递给 C++ 方法.我的 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
}

MyJNIMethod 内部,我必须调用一个 C++ 方法并将从 Java 获取的 2D 浮点数组传递给该方法

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])
    {

    }

由于缺乏本地开发知识,我很难将 jobject 正确转换为 float[][].谁能告诉我最简单和最安全的方法?谢谢

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 ;)
}

请注意,这是大纲.它不会编译;)(我在这个 overstacks 的编辑器中写的)

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);

在你的c代码中对应:

JNIEXPORT jboolean JNICALL Java_ClassName_methodName (JNIEnv *, jobject, jobjectArray);

这里是 JNI 数组操作文档.

相关文章