JNI system.out和printf行为

Mau*_*ice 7 c java java-native-interface

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

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");
}
Run Code Online (Sandbox Code Playgroud)

JNIEXPORT int JNICALL Java_Hello_sayHello (JNIEnv *env, jobject obj) {
     printf("Hello JNI\n");
     return 10;
}
Run Code Online (Sandbox Code Playgroud)

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

before
10
after
Hello JNI
Run Code Online (Sandbox Code Playgroud)

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

Ell*_*sch 17

是.你需要打电话flush.

C,这是fflush电话 -

printf("Hello JNI\n");
fflush(stdout);
return 10;
Run Code Online (Sandbox Code Playgroud)

Java,这只是流上的同花顺 -

System.out.println("before");
System.out.flush();
Run Code Online (Sandbox Code Playgroud)