Simplest way to pass float[][] to C++ via JNI(通过 JNI 将 float[][] 传递给 C++ 的最简单方法)
问题描述
在我的 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 数组操作文档.
这篇关于通过 JNI 将 float[][] 传递给 C++ 的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过 JNI 将 float[][] 传递给 C++ 的最简单方法


- Eclipse 的最佳 XML 编辑器 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 转换 ldap 日期 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01