JNI system.out 和 printf 行为

2022-01-25 00:00:00 c java java-native-interface

我正在编写一个程序,它使用 JNI 与一个简单的 c 程序交互.我创建了以下程序:

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");
}

JNIEXPORT int JNICALL Java_Hello_sayHello (JNIEnv *env, jobject obj) {
     printf("Hello JNI
");
     return 10;
}

令我惊讶的是,这个程序返回:

To my surprise this program returns:

before
10
after
Hello JNI

对我来说这很奇怪,因为很明显 c 程序是在之前"和之后"语句之间执行的(打印数字 10).但是为什么调用时 printf 语句没有执行.jvm是否以某种方式阻止了它,因为只允许一个程序同时写入输出?有没有办法纠正这种行为?

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?

推荐答案

是的.您将需要调用 flush.

Yes. You will need to call flush.

C 中,即 fflush 调用 -

In C, that is the fflush call -

printf("Hello JNI
");
fflush(stdout);
return 10;

Java 中,就是 刷新 在流上 -

In Java, that is just flush on the Stream -

System.out.println("before");
System.out.flush();

相关文章