1 2 3 4 5 6 7 8 9
| JNIExport jint JNICALL Java_IntArray_sumArray(JNIEnv *env, jobject obj, jintArray arr){ jsize len = *env->GetArrayLength(env,arr); jint *body = *env->GetIntArrayElements(env,arr,0); for (jint i = 0; i < len; ++i){ sum += body[i]; } *env->ReleastIntArrayElements(env, arr, body, 0); } |
JNI Function | Description |
Get<Type>ArrayRegion Set<Type>ArrayRegion | Copies the contents of primitive arrays to or from a pre-allocated C buffer. |
Get<Type>ArrayElements Release<Type>ArrayElements | Obtains a pointer to the contents of a primitive array. May return a copy of the array. |
GetArrayLength | Returns the number of elements in the array. |
New<Type>Array | Creates an array with the given length. |
GetPrimitiveArrayCritical ReleasePrimitiveArrayCritical | Obtains or releases a pointer to the contents of a primitive array. These functions allow virtual machines to disable garbage collection while the native code accesses the contents of primitive arrays. |
JNI Array Example program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class SortArray { private native int[] sort(int[] arr); //native method static //static initializer code { System.loadLibrary("SortArray"); } public static void main(String[] args) { int iArr[] = {4,5,2,7,1,9}; // Input array int oArr[]; //Output array SortArray arr = new SortArray(); System.out.println("Unsorted array: "); for(int i = 0; i < iArr.length; i++){ System.out.println(iArr[i] + " "); } oArr = arr.sort(iArr); System.out.println("Sorted array: "); for(int i = 0; i < oArr.length; i++){ System.out.println(oArr[i] + " "); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| /* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class SortArray */ #ifndef _Included_SortArray #define _Included_SortArray #ifdef __cplusplus extern "C" { #endif /* * Class: SortArray * Method: sort * Signature: ([I)[I */ JNIEXPORT jintArray JNICALL Java_SortArray_sort (JNIEnv *, jobject, jintArray); #ifdef __cplusplus } #endif #endif |
The C++ implementation file SortArray.cpp will be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| #include "SortArray.h" #include "jni.h" /* * Class: SortArray * Method: sort * Signature: ([I)[I */ JNIEXPORT jintArray JNICALL Java_SortArray_sort (JNIEnv *env, jobject obj, jintArray arr){ jsize arrLength = env->GetArrayLength(arr); jintArray arrSorted = env->NewIntArray(arrLength); jint *arrOut = NULL; arrOut = env->GetIntArrayElements(arr, 0); for(jsize x = 0; x < arrLength; x++){ for(jsize y = 0; y < arrLength - 1; y++){ if(arrOut[y] > arrOut[y+1]){ jsize temp = arrOut[y+1]; arrOut[y+1] = arrOut[y]; arrOut[y] = temp; } } } env->SetIntArrayRegion(arrSorted, 0, arrLength, arrOut); env->ReleaseIntArrayElements(arr, arrOut, 0); return arrSorted; } |
No comments:
Post a Comment