JNI system.out 和 printf 行为

JNI system.out and printf behaviour(JNI system.out 和 printf 行为)

本文介绍了JNI system.out 和 printf 行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,它使用 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();

这篇关于JNI system.out 和 printf 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:JNI system.out 和 printf 行为

基础教程推荐