JNI在C中将jint转换为native int

时间:2017-04-21 08:19:37

标签: java c java-native-interface

我在FileOutputStream.java中声明了以下函数

public native void write(int b) throws IOException;

我已经在this thread中读到,为了将jint参数转换为native int,你只需要转换它。我的代码:

JNIEXPORT void JNICALL Java_FileOutputStream_write__I(JNIEnv* jni, jobject obj, jint b){
    int native_b = (int)b;
    printf(b);
}

如果我在java中调用该函数,则会收到以下错误消息:

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00007ffc7e01f3b2, pid=8700, tid=0x00000000000020e4
#
# JRE version: Java(TM) SE Runtime Environment (8.0_112-b15) (build 1.8.0_112-b15)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.112-b15 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# C  [msvcrt.dll+0x4f3b2]
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# <my_path>\JNI\hs_err_pid8700.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

所以我猜我的演员是错的。为了做到这一点,我该怎么做?

1 个答案:

答案 0 :(得分:3)

转换printf没有错,但char *期望带有参数的格式字符串。

您的代码尝试访问地址b的{​​{1}},因为b不是崩溃的实际地址。查找编译器{(1}}的文档(或任何printf文档,例如:https://linux.die.net/man/3/printf)。