0

Just getting started with JNI, and not sure why the log messages in C don't post to the terminal until after the app terminates.

public static native long initialize(String arg);
public static native boolean hasImage();
public static native void dispose();

public static void main(String[] args) {
    long id = ClipboardHelper.initialize("");
    System.out.println(id);

    try {
        System.in.read(); //wait for enter key
    } catch (IOException e) {
    }
    ClipboardHelper.dispose();
}

C code:

JNIEXPORT jlong JNICALL Java_com_mypackage_ClipboardHelper_initialize
(JNIEnv *env, jclass obj, jstring arg) {
    printf("hello world");
    return 1;
}

When I run the app, I see it print 1 from the Java println method call:

1

But it doesn't print hello world until I hit the enter key to continue the app.

1
hello world

I can see that the C function returned, because the correct number was printed in Java. In fact, I can call several native methods and only after I press enter do all the queued up printf message appear.

Tenfour04
  • 39,254
  • 8
  • 47
  • 96
  • 4
    `printf` is line buffered by default. So it won't actually flush to stdout until a newline is encountered. Or an explicit flush (which does happen on app exit). So either end the printf string with a `\n` or explicitly call `fflush(stdout)`. – kaylum Jun 17 '16 at 03:41
  • 6
    see http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – wero Jun 17 '16 at 03:43
  • Thanks. I was assuming I was running into a JNI oddity. :/ – Tenfour04 Jun 17 '16 at 03:57

0 Answers0