JNI System.out和printf的行为 [英] JNI system.out and printf behaviour

查看:778
本文介绍了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\n");
     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?

推荐答案

是的。您将需要调用刷新

Yes. You will need to call flush.

C ,也就是 fflush 电话 -

In C, that is the fflush call -

printf("Hello JNI\n");
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的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆