java - JNI 返回类型

标签 java c java-native-interface

我可以使用返回指针的 native 方法吗?
我使用了以下语法: 公共(public) native int* intArrayMethod(float[] t,int nb_of_subscribers,int 标签); 但它表明有错误。

最佳答案

由于 C++ 和 Java 之间的数据结构存在差异,您不应在 Java 中使用 native 指针。还有 Java 的垃圾收集器。

您的 Java 类应如下所示:

    public class IntArrayViaJNI {
      private static boolean loaded = false;
      private native int[] intArrayMethod(float[] t, int nb_of_subscribers, int tags);

      public int[] getIntArray(float[] t, int nb_of_subscribers, int tags) {
          // Although this portion should be in a synchronized method,
          // e.g. ensureLibraryLoaded().
          if (!loaded) {
            System.loadLibrary("mylib");
            loaded = true;
          }
          return intArrayMethod(t, nb_of_subscribers, tags);
      }
    }

您的 C++ 代码应如下所示:

    JNIEXPORT jintArray JNICALL Java_IntArrayViaJNI_intArrayMethod(
        JNIEnv *env, jclass cls,
        /* generated by JAVAH: float[] t, int nb_of_subscribers, int tags */)
    {
      jintArray result = (*env)->NewIntArray(env, size);
      if (result == NULL) {
        return NULL; /* out of memory error thrown */
      }
      int i, size = MY_ARRAY_SIZE;

      // Populate a temp array with primitives.
      jint fill[256];
      for (i = 0; i < size; i++) {
        fill[i] = MY_ARRAY_VALUE;
      }

      // Let the JVM copy it to the Java structure.
      (*env)->SetIntArrayRegion(env, result, 0, size, fill);
      return result;
    }

关于java - JNI 返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9998377/

相关文章:

java - 使用调用 API 的 JNI 内存管理

Java ActiveMQ - 如何将过期消息发送到另一个队列

c - 尝试使用 scanf 读取数字时程序崩溃

c - C中将字符串拆分为多个子字符串

c - JNI中如何通过引用传递?

android - OpenSSL 库中的链接错误

java - 你如何链接多个可观察对象?

Java:在 URLConnection 中恢复下载

java - Android onTouchEvent 在 View 类中

Cuda - 大数组初始化