JNI GetShortArrayElements失败,出现SIGSEGV SEGV_ACCERR

时间:2015-11-08 02:42:08

标签: java android c++ java-native-interface kotlin

我在托管代码中创建了一个缓冲区:

var nativeBuffer = ShortArray(bufferSize)

这是Kotlin代码,但根据stdlib documentation,此语法实际上是一个返回short []的包装器。

然后我想使用JNI从C ++写入此缓冲区:

JNIEXPORT void JNICALL Java_package_class_name_readNext
    (JNIEnv * env, jclass clazz, jshortArray javaArray)
{
    jboolean * isCopy;
    short * targetArray = env->GetShortArrayElements(javaArray, isCopy);

    // Do stuff to targetArray
}

问题是GetShortArrayElements调用总是会导致崩溃,并使用以下逻辑删除:

11-07 21:23:53.610 86-86/? I/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
11-07 21:23:53.610 86-86/? I/DEBUG: Build fingerprint: 'generic/vbox86p/vbox86p:5.1/LMY47D/buildbot06092001:userdebug/test-keys'
11-07 21:23:53.610 86-86/? I/DEBUG: Revision: '0'
11-07 21:23:53.610 86-86/? I/DEBUG: ABI: 'x86'
11-07 21:23:53.610 86-86/? I/DEBUG: pid: 28339, tid: 28477, name: Thread-282  >>> <package-name> <<<
11-07 21:23:53.610 86-86/? I/DEBUG: signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 0xb3bcfacb
11-07 21:23:53.613 86-86/? I/DEBUG:     eax b3bcfacb  ebx b3ffcaa4  ecx a2497000  edx b426e480
11-07 21:23:53.613 86-86/? I/DEBUG:     esi a2497000  edi b3fff440
11-07 21:23:53.613 86-86/? I/DEBUG:     xcs 00000073  xds 0000007b  xes 0000007b  xfs 000000e7  xss 0000007b
11-07 21:23:53.613 86-86/? I/DEBUG:     eip b3dcd69c  ebp 9f5a2968  esp 9f5a2880  flags 00210282
11-07 21:23:53.613 86-86/? I/DEBUG:     #00 pc 002e069c  /system/lib/libart.so (short* art::JNI::GetPrimitiveArray<_jshortArray*, short, art::mirror::PrimitiveArray<short> >(_JNIEnv*, _jshortArray*, unsigned char*)+572)
11-07 21:23:53.613 86-86/? I/DEBUG:     #01 pc 0010cdad  /system/lib/libart.so (art::CheckJNI::GetShortArrayElements(_JNIEnv*, _jshortArray*, unsigned char*)+125)

javaArray不为空(通常是地址,如-1621480864),nativeBuffer是静态变量,所以不太可能是GC。行为发生在Genymotion实例(x86)和ARM设备上,但我只针对Android 5.0+进行了测试。还有什么我可以错过的?

2 个答案:

答案 0 :(得分:3)

糟糕,您没有正确使用isCopy参数。它应该是:

jboolean isCopy;
jshort* targetArray = env->GetShortArrayElements(javaArray, &isCopy);

也就是说,isCopy是一个“out参数”(使用C#lingo)。

如果您不关心targetArray是否为javaArray别名,您也可以改为nullptr,如下所示:

jshort* targetArray = env->GetShortArrayElements(javaArray, nullptr);

答案 1 :(得分:3)

目标数组应为 jshort ,而不是

您还需要使用&amp; 而不是按值传递 isCopy

更多信息: http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html#wp17382