문제

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?

도움이 되었습니까?

해결책

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top