如何从 C 文件函数(Java 本机接口)仅调用 return 值到 Java

How to call only the return value to Java from a C file function (Java Native Interface)

我有一个 Java 文件,它声明了在我的 C 文件中定义的本机方法 average()。该方法取两个数字的平均值,打印“在 C 中,数字是 n1、n2”(n1 和 n2 是输入数字),returns 是双精度数。

然后Java文件调用average()方法,打印“In Java, average is (n1 + n2)/2”然后打印平均值x 2。

这是一个数字 3 和 2 的示例(运行 我的 Java 文件):

In C, the numbers are 3 and 2

In Java, the average is 2.5

In C, the numbers are 3 and 2

5.0

我只想将 C 文件中的 return 值(平均值)乘以 2。我不想打印字符串“In C, the numbers are 3 and 2”再次。如何仅打印 C 文件中的 return 值(平均值)而不再次打印字符串“In C, the numbers are 3 and 2”?我知道我可以创建另一种方法,但这会非常重复。

我的 Java 文件如下:

public class TestJNIPrimitive {
    
    static {
        System.loadLibrary("myjni"); //myjni.dll (Windows)
    }

    private native double average(int n1, int n2);
    public static void main(String args[]) {
        
        System.out.println("In Java, the average is " + new TestJNIPrimitive().average(3,2));
        double result = new TestJNIPrimitive().average(3,2);
        System.out.println(result*2);
    }
}

我的C文件如下:

JNIEXPORT jdouble JNICALL Java_TestJNIPrimitive_average(JNIEnv *env, jobject thisObj, jint n1, jint n2) {
    
    printf("In C, the numbers are %d and %d\n", n1, n2);
    jdouble result;
    result = ((jdouble)n1 + n2) / 2.0;
    // jint is mapped to int, jdouble is mapped to double
    return result;
}

感谢您的帮助!

除非我遗漏了什么,你可以简单地 not 调用你的 C average 函数两次,并在调用一次后存储结果:

public static void main(String args[]) {
    double result = new TestJNIPrimitive().average(3,2);
    System.out.println("In Java, the average is " + result);
    System.out.println(result*2);
}