jni jiniArray作为输出参数不会更改参数的值 [英] jni jiniArray as output parameter doesn't change values of parameter
本文介绍了jni jiniArray作为输出参数不会更改参数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从c ++程序调用Java静态方法,我有以下Java代码:
I'm trying to call java static method from c++ program, I've got this java code:
public static int[] arrayFunc(int [] array) {
int [] newArray = copyOf(array, array.length);
for(int i = 0; i < newArray.length; ++i) {
newArray[i] += 1;
}
return newArray;
}
然后在cpp代码中,我有:
Then in cpp code I have:
// JNIEnv *env is created before I call function
jintArray CallStaticFunction(const char* functionName, const int* parameter, const size_t size) {
jmethodID mid = env->GetStaticMethodID(cls, functionName, "([I)[I");
for(size_t i=0;i<size;++i) {
printf("parameter = %d\n", parameter[i]);
}
if (mid) {
jintArray iarr = env->NewIntArray(size);
env->SetIntArrayRegion(iarr, 0, size, parameter);
jintArray array = (jintArray)env->CallStaticObjectMethod(cls, mid, iarr);
return array;
} else {
printf("find statis int method failed\n");
exit(3);
}
}
在main.cpp中,我已经:
And in main.cpp I've:
env = ... //all the jvm initializatin work
int buf[3];
for(int i=0;i<3;++i){
buf[i] = i;
}
jintArray ret = CallStaticFunction("arrayFunc", buf, 3);
for(int i=0;i<3;++i){
printf("%d\n", ret[i]);
}
输出为:
parameter = 0
parameter = 1
parameter = 2
0
0
0
我希望最后3行应为 1 2 3。但实际上不是。那么我的程序在哪里出错了,以及如何解决它?
I expected that the last 3 lines should be "1 2 3". But actually not. So where did I get wrong in my program, and how to fix it?
非常感谢。
推荐答案
您不能将 jintArray
作为常规C数组进行访问。您需要使用适当的JNI函数来访问数据:
You can't access a jintArray
as a regular C array. You need to use the appropriate JNI functions to gain access to the data:
jintArray ret = CallStaticFunction("arrayFunc", buf, 3);
int *p = env->GetIntArrayElements(ret, NULL);
for(int i=0;i<3;++i){
printf("%d\n", p[i]);
}
env->ReleaseIntArrayElements(ret, p, JNI_ABORT);
请参考文档以获得有关这些功能如何工作的更多详细信息。
Refer to the documentation for more details on how these functions work.
这篇关于jni jiniArray作为输出参数不会更改参数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文