问题
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[]
)?
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;
}
but it fails to compile, saying:
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];
回答1:
You must use jni functions, there are at least two methods:
Copy a region:
jchar buf[10];
(*env)->GetCharArrayRegion(env, bits, 0, 10, buf);
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);
Here I assume your array is 10 elements in length. To find out number of elements in the array use GetArrayLength
jni function.
来源:https://stackoverflow.com/questions/38882650/how-to-convert-a-jchararray-to-a-char-in-c