1. 編譯java:javac JNIDemo.javajava
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.clinux
export LD_LIBRARY_PATH=.數組
3. 執行:java JNIDemojvm
字段描述符取巧辦法:spa
1. javac JNIDemo.java字符串
2. javah -jni JNIDemostring
生成一個頭文件:JNIDemo.hio
字符串的傳遞:編譯
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");gcc
數組的傳遞:
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;