如何从 JNI 中的 GetDirectBufferAddress 调用多种数据类型?

2022-01-25 00:00:00 c java java-native-interface

我通过本机方法得到一个 bytebuffer.

I get a bytebuffer via the native methods.

bytebuffer 以 3 个 int 开头,然后只包含双精度.第三个 int 告诉我接下来的双打数.

The bytebuffer starts with 3 ints, 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 ints and the remaining doubles, 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
}

相关文章