问题描述
我有一个jcharArray
,它通过Java传递到C程序中,我需要知道如何在C程序中使用数组.如何将我的jcharArray
位转换为可以使用的内容(char bits[]
)?
I have a jcharArray
that is passed into a C program through Java, and I need to know how to use the array in the C program. How do I convert my jcharArray
bits into something I can use (char bits[]
)?
我尝试使用JNI编写此代码
I tried writing this code using JNI
JNIEXPORT jint JNICALL Java_ex_NistStatisticalTestSuite_frequency
(JNIEnv *env, jclass cls, jcharArray bits, jint jn)
{
printf("running frequency test");
int i;
double f, s_obs, p_value, sum, sqrt2 = 1.41421356237309504880;
int n=jn;
char deletethis=(char)bits[0];
sum = 0.0;
for ( i=0; i<n; i++ )
sum += 2*1-1;
s_obs = fabs(sum)/sqrt(n);
f = s_obs/sqrt2;
p_value = erfc(f);
return (jint)p_value;
}
但无法编译,并说:
frequency.c:19:2: error: invalid use of undefined type ‘struct _jobject’
char deletethis=(char)bits[0];
^~~~
frequency.c:19:28: error: dereferencing pointer to incomplete type ‘struct _jobject’
char deletethis=(char)bits[0];
推荐答案
您必须使用jni函数,至少有两种方法:
You must use jni functions, there are at least two methods:
复制区域:
jchar buf[10];
(*env)->GetCharArrayRegion(env, bits, 0, 10, buf);
在JVM中锁定一个内存区域,然后对其进行访问并最终释放:
lock a memory region in JVM, then access it and finally release:
jchar *carr;
carr = (*env)->GetCharArrayElements(env, bits, NULL);
if (carr == NULL) {
return 0; /* exception occurred */
}
//for (int i=0; i<10; i++) {
// do something with carr[i];
//}
(*env)->ReleaseCharArrayElements(env, bits, carr, 0);
在这里,我假设您的数组长度为10个元素.要找出数组中元素的数量,请使用GetArrayLength
jni函数.
Here I assume your array is 10 elements in length. To find out number of elements in the array use GetArrayLength
jni function.
这篇关于如何在c中将jcharArray转换为char []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!