我可以使用返回指针的 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/