How do I call multiple data types from GetDirectBufferAddress in JNI?(如何从 JNI 中的 GetDirectBufferAddress 调用多种数据类型?)
问题描述
我通过本机方法得到一个 bytebuffer
.
I get a bytebuffer
via the native methods.
bytebuffer
以 3 个 int
开头,然后只包含双精度.第三个 int
告诉我接下来的双打数.
The bytebuffer
starts with 3 int
s, then contains only doubles.
The third int
tells me the number of doubles that follow.
我能够阅读前三个 int
.
为什么当我尝试读取双打时代码会崩溃?
Why is the code crashing when I try to read the doubles?
获取前三个整数的相关代码:
Relevant code to get the first three integers:
JNIEXPORT void JNICALL test(JNIEnv *env, jobject bytebuffer)
{
int * data = (int *)env->GetDirectBufferAddress(bytebuffer);
}
获取剩余双打的相关代码:
Relevant code to get the remaining doubles:
double * rest = (double *)env->GetDirectBufferAddress(bytebuffer + 12);
推荐答案
在您发布的代码中,您正在调用:
In your posted code, you are calling this:
double * rest = (double *)env->GetDirectBufferAddress(bytebuffer + 12);
这会将 12 添加到 bytebuffer
jobject
,这不是数字.
This adds 12 to the bytebuffer
jobject
, which not a number.
GetDirectBufferAddress()
返回地址;由于前 3 个 int
每个都是 4 个字节,我相信您正确添加了 12,但是 您没有在正确的位置添加它.
GetDirectBufferAddress()
returns an address; since the first 3 int
are 4 bytes each, I believe you are correctly adding 12, but you are not adding it in the right place.
你可能打算这样做:
double * rest = (double *)((char *)env->GetDirectBufferAddress(bytebuffer) + 12);
对于您的整体代码,要获取最初的三个 int
和剩余的 double
,请尝试类似以下操作:
For your overall code, to get the initial three int
s and the remaining double
s, try something similar to this:
void * address = env->GetDirectBufferAddress(bytebuffer);
int * firstInt = (int *)address;
int * secondInt = (int *)address + 1;
int * doubleCount = (int *)address + 2;
double * rest = (double *)((char *)address + 3 * sizeof(int));
// you said the third int represents the number of doubles following
for (int i = 0; i < doubleCount; i++) {
double d = *rest + i; // or rest[i]
// do something with the d double
}
这篇关于如何从 JNI 中的 GetDirectBufferAddress 调用多种数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 JNI 中的 GetDirectBufferAddress 调用多种数据类型?


基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01