JNI——JAVA调用C
1. 编译java:javac JNIDemo.java
2. 编译JNI:gcc -I/usr/lib/jvm/java-1.8.0-openjdk-amd64/include/ -I/usr/lib/jvm/java-1.8.0-openjdk-amd64/include/linux/ -fPIC -shared -o libnative.so native.c
export LD_LIBRARY_PATH=.
3. 执行:java JNIDemo
字段描述符取巧办法:
1. javac JNIDemo.java
2. javah -jni JNIDemo
生成一个头文件:JNIDemo.h
字符串的传递:
const jbyte *cstr;
cstr = (*env)->GetStringUTFChars(env, str, NULL);
if(cstr == NULL)
{
return NULL;
}
printf("Get string from java: %s\n", cstr);
(*env)->ReleaseStringUTFChars(env, str, cstr);
return (*env)->NewStringUTF(env, "return from c");
数组的传递:
jint *carr;
jint i, sum = 0;
carr = (*env)->GetIntArrayElements(env, arr, NULL);
if(carr == NULL)
{
return 0;
}
for(i = 0; i < (*env)->GetArrayLength(env, arr); i++)
{
sum += carr[i];
}
(*env)->ReleaseIntArrayElements(env, arr, carr, 0);
return sum;
传入数组参数,返回数组参数:
jint *carr;
jint *oarr;
jintArray rarr;
jint i, n = 0;
carr = (*env)->GetIntArrayElements(env, arr, NULL);
if(carr == NULL)
{
return 0;
}
n = (*env)->GetArrayLength(env, arr);
oarr = malloc(sizeof(jint) * n);
if(oarr == NULL)
{
(*env)->ReleaseIntArrayElements(env, arr, carr, 0);
return 0;
}
for(i = 0; i < n; i++)
{
oarr[i] = carr[n - 1 - i];
}
/* crate jintArray */
rarr = (*env)->NewIntArray(env, n);
if(rarr == NULL)
{
return 0;
}
(*env)->SetIntArrayRegion(env, rarr, 0, n, oarr);
free(oarr);
return rarr;