Vilib
Vilib

Reputation: 93

JNI convert jint to native int in C

I've the following function declared in FileOutputStream.java

public native void write(int b) throws IOException;

I've read in this thread that for converting the jint parameter to a native int you simply have to cast it. My c code:

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

If I call the function in java, I get the following error message:

#
# 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.
#

So I guess my cast is wrong. What do I have to do to get it right?

Upvotes: 3

Views: 14604

Answers (1)

user2543253
user2543253

Reputation: 2173

Nothing wrong with casting the jint, but printf expects a format string with arguments.

Your code tries to access the char * at address b and since b is not an actual address it crashes. Lookup the documentation for printf for your compiler (or just any printf documentation, this one for example: https://linux.die.net/man/3/printf).

Upvotes: 6

Related Questions