通过JNI将float [] []传递给C ++的最简单的方法 [英] Simplest way to pass float[][] to C++ via JNI
问题描述
在我的Java代码中,我有一个2D浮点数组 float [x] [4] floatArray
。这里 x
可以在1和25之间。我必须通过 C ++
c $ c> JNI 。我的 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
推荐答案
这样应该可以工作:
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 ;)
}
注意这是大纲。
在你的类中,你应该声明一个本地方法:
In your class you should declare native method:
public native void myJNIMethod(float[][] m);
并在您的c代码中对应:
and in your c code corresponding:
JNIEXPORT jboolean JNICALL Java_ClassName_methodName (JNIEnv *, jobject, jobjectArray);
这里是 JNI数组操作文档。
这篇关于通过JNI将float [] []传递给C ++的最简单的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!