java - 如何在JNI中将指针从java传递到C?

2022-01-25 00:00:00 pointers java java-native-interface

我有一个本地方法 int sum(int *,int *).我如何从 java 端传递这个方法的参数.

i have a native method int sum(int *,int *).How do i pass the parameters for this method from java side.

我成功运行的示例方法是双 gsl_stats_mean(doubleArray,int,int);这个方法在 GSL 中可用,因为我已经创建了共享对象,并且从 java 端我已经发送了所需的参数,并且我得到了 double 作为返回值.

the example method which i ran successfully is double gsl_stats_mean(doubleArray,int,int); this method is available in GSL ,for that i have created shared object and from java side i had sent required parameters and i got the double as a return value.

推荐答案

如果方法没有改变引用的值,那么你只需将参数作为值传递,并在本机代码中获取它们的地址:

If the method doesn't change the referenced values, then you just pass parameters as values, and get their addresses in native code:

JNIEXPORT jint JNICALL Java_com_example_Summator_sum(JNIEnv *env, jobject thisObj,
        jint firstAddend, jint secondAddend) {
     return (jint) sum(&firstAddend, &secondAddend);
}

而Java中的方法是:

And the method in Java is:

native int sum(int firstAdded, int secondAddend);

显然,除了 sum 函数之外,您在任何地方都不需要指针,因此没有理由在 Java 中使用它们.

Apparently you don't need the pointers anywhere except in the sum function, so there is no reason to work with them in Java.

相关文章