CallVoidMethod中的SIGSEGV jni

时间:2015-06-29 19:11:17

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

我有一些带有一些jni原生方法的java应用程序。其中一个是readFile,它被称为:

OutputStream outStream = null;
File file = new File("Alf.txt");

try {
    outStream = new FileOutputStream(file);
    myObject.readFile("TestFile.txt",outStream);
...

在我的jni实现中我做了:

JNIEXPORT jint JNICALL Java_com_example_mylib_SomeClass_readFile
(JNIEnv *env, jclass, jstring java_string, jobject stream) {


jclass classOutputStream = env->FindClass("java/io/OutputStream");
if (classOutputStream == NULL)
{
      Log::err("classOutputStream == NULL;");
      return -1;
}
jmethodID OutputStream_write_ID = env->GetMethodID(classOutputStream, "write", "([BII)V");
if (OutputStream_write_ID == NULL)
{
   return -1;
}
char* buf = "hello";

env->CallVoidMethod((jobject)stream, OutputStream_write_ID,buf,0,5);

当我调用CallVoidMethod时,我得到了

# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007f4a85a5e1e1, pid=25597, tid=139958068348672
#
# JRE version: Java(TM) SE Runtime Environment (8.0_25-b17) (build 1.8.0_25-b17)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.25-b02 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# V  [libjvm.so+0x6ad1e1]  jni_GetArrayLength+0xb1
#
# Failed to write core dump. Core dumps have been disabled. To enable  core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /.../hs_err_pid25597.log

我检查过 - 没有变量== NULL,我做错了什么?

1 个答案:

答案 0 :(得分:0)

C char数组与Java字节数组对象不可互换 - 创建和复制数据需要一些工作。

    int len = strlen(buf);
    jbyteArray arr = (*env)->NewByteArray(env, len);
    (*env)->SetByteArrayRegion(env, arr, 0, len, (jbyte*)buf);

如果你需要一个字符串,那就更容易了:

    jstring jString = (*env)->NewStringUTF( env, buf );