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

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

bytebuffer以3 int开头,然后只包含双精度。 第三个int告诉我后面的双打数量。

我能够读到前三个int

当我尝试阅读双打时,为什么代码会崩溃?

获取前三个整数的相关代码:

 JNIEXPORT void JNICALL test(JNIEnv *env, jobject bytebuffer) { int * data = (int *)env->GetDirectBufferAddress(bytebuffer); } 

获得剩余双打的相关代码:

 double * rest = (double *)env->GetDirectBufferAddress(bytebuffer + 12); 

在您发布的代码中,您称之为:

 double * rest = (double *)env->GetDirectBufferAddress(bytebuffer + 12); 

这为bytebuffer jobject增加了12,而不是数字。

GetDirectBufferAddress()返回一个地址; 因为前3个int每个都是4个字节,我相信你正确地添加12个,但是你没有在正确的位置添加它

你可能想要做的是:

 double * rest = (double *)((char *)env->GetDirectBufferAddress(bytebuffer) + 12); 

对于你的整体代码,要获得最初的三个int和剩余的double s,尝试类似于此的东西:

 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 }