I am writing a program that uses JNI to interface with a simple c program. I have created the following programs:
public static void main(String[] args) {
Hello h = new Hello();
System.out.println("before");
int number = h.sayHello();
System.out.println(number);
System.out.println("after");
}
and
JNIEXPORT int JNICALL Java_Hello_sayHello (JNIEnv *env, jobject obj) {
printf("Hello JNI\n");
return 10;
}
To my surprise this program returns:
before
10
after
Hello JNI
To me this is very strange because it is clear that the c program is executed between the "before" and "after" statement (The number 10 is printed). But why is the printf statement not executed when it is called. Is it somehow blocked by the jvm because only one program is allowed to write to the output at the same time? Is there a way to correct this behavior?
JNI is the Java Native Interface. It defines a way for the bytecode that Android compiles from managed code (written in the Java or Kotlin programming languages) to interact with native code (written in C/C++).
Java Native Access (JNA) is a community-developed library that provides Java programs easy access to native shared libraries without using the Java Native Interface (JNI). JNA's design aims to provide native access in a natural way with a minimum of effort. Unlike JNI, no boilerplate or generated glue code is required.
When talking about JNI, there are two directions: java calling C++, and C++ calling java. Java calling C++ (or C) via the "native" keyword is very fast, around 50 clock cycles. However, C++ calling Java is somewhat slow.
The JNI is a native programming interface. It allows Java code that runs inside a Java Virtual Machine (VM) to interoperate with applications and libraries written in other programming languages, such as C, C++, and assembly.
Yes. You will need to call flush
.
In C
, that is the fflush call -
printf("Hello JNI\n");
fflush(stdout);
return 10;
In Java
, that is just flush on the Stream -
System.out.println("before");
System.out.flush();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With