use*_*459 -3 c java java-native-interface ffi
我有一个jcharArray通过Java传递到C程序,我需要知道如何在C程序中使用该数组.如何将我的jcharArray位转换为可以使用的东西(char bits[])?
我尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)
但它无法编译,说:
Run Code Online (Sandbox Code Playgroud)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函数,至少有两种方法:
复制区域:
jchar buf[10];
(*env)->GetCharArrayRegion(env, bits, 0, 10, buf);
Run Code Online (Sandbox Code Playgroud)
锁定JVM中的内存区域,然后访问它并最终释放:
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);
Run Code Online (Sandbox Code Playgroud)
这里我假设你的数组长度为10个元素.要找出数组中的元素数,请使用GetArrayLengthjni函数.