我使用JNI在Java中编程。 我已经通过NetBeans进行了全部配置。
在C方法中调用Java方法时,获得的结果显示在同一C方法中的其他操作之前。我附上一些代码。
这里是C代码,在main中调用两次:
JNIEXPORT void JNICALL Java_jnidemojava_Main_myprint
(JNIEnv *env, jobject obj){
jfieldID fldid;
jint nx, nnx;
(void)printf("Hello from a Native Method\n");
if (obj == NULL) {
fprintf(stderr, "Input pointer is null!\n");
return;
}
if ((fldid = (*env)->GetFieldID(env,
(*env)->GetObjectClass(env, obj), "x", "I")) == NULL) {
fprintf(stderr, "GetFieldID failed");
return;
}
nx = (*env)->GetIntField(env, obj, fldid);/* retrieve myNumber */
printf("\"myNumber\" value is %d\n", nx);
(*env)->SetIntField(env, obj, fldid, ++nx);/* increment it! */
nnx = (*env)->GetIntField(env, obj, fldid);
printf("\"myNumber\" value now %d\n", nnx); /* make sure */
if(nnx==10){
//richiama un metodo di Main
//jclass myClass = (*env)->FindClass(env, "Main");
jclass myClass = (*env)->GetObjectClass(env, obj);
jmethodID myMethod = (*env)->GetMethodID(env, myClass, "method", "(I)V");
int c=100;
(*env)->CallIntMethod(env, obj, myMethod,c);
printf("CALLED!");
}
这里是C:
调用的java方法public void method(int c) throws InterruptedException{
System.out.println("Method called from C "+c);
}
一切都好,但我不明白为什么输出顺序错误。
输出
Method called from C 100
"myNumber" value is 8
"myNumber" value now 9
"myNumber" value is 9
"myNumber" value now 10
CALLED!
BUILD SUCCESSFUL (total time: 0 seconds)
谢谢。