这是以下问题的后续:
由于
GetPrimitiveArrayCritical
不起作用,我选择了 Direct ByteBuffer
,下面是我的 java 端代码:
ByteBuffer buf = ByteBuffer.allocateDirect(arr.length * 4); // arr is a float array
buffer.order(ByteOrder.nativeOrder());
FloatBuffer fb = buffer.asFloatBuffer();
fb.put(arr);
fb.position(0);
native int calculate(FloatBuffer fb);
在JNI方面我有以下代码:
JNIExport jint JNICALL Java_com_test_calculate(JNIEnv *env, jobject obj, jobject arr){ // the arr has the buffer
jfloat *ptr = NULL
void *temp = (*env) -> GetDirectBufferAddress(env, arr);
*ptr = *(jfloat *)&temp;
...
...
MBufGet(srcBuf, ptr); //matrox imaging lib call - This has to fill the array from srcBuf
}
在Java中我通过以下方式访问它:
float[] arr = new float[buffer.capacity()/4];
for(int i=0; i<buffer.capacity()/4;i++){
arr[i] = buffer.getFloat();
}
这没有错误,但检索到的 arr 仅包含 0 / 或未更新缓冲区。
如果我使用下面的代码(带有
GetFloatArrayElements
),这些逻辑就有效:
JNIExport jint JNICALL Java_com_test_calculate(JNIEnv *env,jobject obj, jfloatArray arr){ // the arr has the buffer
jfloat *ptr = NULL
*ptr = (*env) -> GetFloatArrayElements(env, arr, 0);
...
...
MBufGet(srcBuf, ptr); //matrox imaging lib call - This has to fill the array from srcBuf
}
我认为它可以工作,因为它本身有一个实际的数组指针,并且在直接缓冲区的情况下有些东西是错误的。
如何让直接
GetDirectBufferAddress
返回与 JNI 中 GetFloatArrayElements
返回类似的类型。
你完全搞砸了演员阵容。应该是
jfloat *ptr = (jfloat *)((*env)->GetDirectBufferAddress(env, arr));