JNI堆栈顺序误解
我在一个非常简单的 JNI 示例(Java + C)中有以下代码
Java
package jnitest;
public class JNITest {
static {
System.load("C:/.../JNItestNative.dll");
}
public native void hello();
public static void main(String[] args) {
JNITest jniTest = new JNITest();
System.out.println("Hello in java");
jniTest.hello();
System.out.println("Bye in java");
}
}
C
/*
* File: jnitestnative.c
* Author: DEFAULT
*
* Created on February 17, 2012, 12:24 PM
*/
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
JNIEXPORT void JNICALL Java_jnitest_JNITest_hello
(JNIEnv *env, jobject obj) {
printf("Hello in C\n");
printf("Bye in C\n");
return;
}
我希望结果是这样的:
Hello in Java
Hello in C
Bye in C
Bye in Java
但它确实是这样的:
Hello in java
Bye in java
Hello in C
Bye in C
I have the following code in a very simple JNI example (Java + C)
Java
package jnitest;
public class JNITest {
static {
System.load("C:/.../JNItestNative.dll");
}
public native void hello();
public static void main(String[] args) {
JNITest jniTest = new JNITest();
System.out.println("Hello in java");
jniTest.hello();
System.out.println("Bye in java");
}
}
C
/*
* File: jnitestnative.c
* Author: DEFAULT
*
* Created on February 17, 2012, 12:24 PM
*/
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
JNIEXPORT void JNICALL Java_jnitest_JNITest_hello
(JNIEnv *env, jobject obj) {
printf("Hello in C\n");
printf("Bye in C\n");
return;
}
I expect the result to be like this:
Hello in Java
Hello in C
Bye in C
Bye in Java
But it is really like this:
Hello in java
Bye in java
Hello in C
Bye in C
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当我运行您发布的代码时,我得到了预期的输出。由于 stdout 由标准 C 库缓冲,而 JVM 倾向于绕过 C 库并直接使用操作系统调用,因此可能会发生一些奇怪的缓冲。
如果是这种情况,您始终可以在从 C 返回之前刷新
stdout
:When I run the code you posted I get the expected output. There may be some strange buffering going on due to the fact that
stdout
is buffered by the standard C library, while the JVM tends to bypass the C library and use OS calls directly.If this is the case you can always flush
stdout
before returning from C: