gpt4 book ai didi

java - Android NDK 将 3D float 组传递给 C 代码

转载 作者:太空宇宙 更新时间:2023-11-04 01:12:30 26 4
gpt4 key购买 nike

我想将 3d float 组(float[][][])从 java 传递给 c 编辑它并将数组返回给 java
Curretly 我只能用一维数组来做到这一点

jfloat* valuesjf = NULL;
float* valuesf = NULL;
void Java_Grids_Grid5_Update( JNIEnv* env,jobject thiz,jfloatArray values )
{
valuesjf = (*env)->GetFloatArrayElements(env,values,NULL);
valuesf = valuesjf;

valuesf[0]=121+valuesf[0];//do some calculations

(*env)->ReleaseFloatArrayElements(env, values, valuesjf, JNI_ABORT);
}

如何使用 3D 阵列来实现?

最佳答案

您可以将 Java 中的 3d float 组展平为 1d 数组。然后,您可以通过在 1d 数组中生成正确的索引来访问原始 3d 数组的每个元素。您还需要将数组每个维度的长度传递给 native 方法,以便 native 方法也可以为一维数组生成正确的索引

Java:

// The lengths of each dimension of the values array
int l, m, n;
// Instead of:
// float[][][] values = new float[l][m][n];
// Do this:
float[] values = new float[l * m * n];

// To access an entry at (x, y, z) in the array.
// Instead of:
// float v = values[z][y][x];
// Do this:
int i = (m * n * z) + (n * y) + x;
float v = values[i];

C++:

// You should not store a reference to the Java array as a global variable.
// The reference is only valid between the Get/ReleaseFloatArrayElements calls
// Since valuesf is assigned the same reference to the Java array,
// the same advice also applies to it
// jfloat* valuesjf = NULL;
// float* valuesf = NULL;

void
Java_Grids_Grid5_Update(JNIEnv* env,
jobject thiz,
jfloatArray values,
jint l, jint, m, jint n) {

jfloat* valuesjf = (*env)->GetFloatArrayElements(env,values,NULL);
float* valuesf = valuesjf;

int x, y, z;
int i = (m * n * z) + (n * y) + x;
valuesf[0]=121+valuesf[i]; //do some calculations

(*env)->ReleaseFloatArrayElements(env, values, valuesjf, JNI_ABORT);

}

关于java - Android NDK 将 3D float 组传递给 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9142674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com