Jump to Real's How-to Main page

Use arrays

JNI provides special functions (relative to the type) to access Java arrays.

This example returns the maximum of an int array.
JNIEXPORT jint JNICALL Java_JavaHowTo_max(JNIEnv * env, jclass obj, jintArray arr)  {
  int i;
  jsize len = env->GetArrayLength(arr, max = -1;
  jint *body = env->GetIntArrayElements(arr, 0);
  for (max = body[0], i=1; i < len; i++)
    if (max < body[i]) max = body[i];
  env->ReleaseIntArrayElements(arr, body, 0);
  return max;
  }
The Java wrapper
class JavaHowTo {
    public static native int max(int [] t);
    static {
        System.loadLibrary("javahowto");
    }
}
The test program
class JNIJavaHowTo {
    public static void main(String[] args) {
        int [] myArray = {4, 7, 5, 9, 2, 0, 1};
        System.out.println(JavaHowTo.max(myArray));
    }
}

This following how-to is currently broken...
Without passing the array directly to the JNI function, it's possible to fetch directly from the class the array.
JNIEXPORT jint JNICALL Java_JavaHowTo_printArray(JNIEnv * env, jclass obj)  {
  jfieldID fid;
  jobject  jtab;
  jsize len;
  int i;
      
  jclass cls = env->GetObjectClass(obj);
  fid = env->GetFieldID(cls, "myArray", "[I");
  if (fid == 0) return;
  jtab = env->GetObjectField(obj, fid);
  tab = env->GetIntArrayElements(jtab, 0);
  len = env->GetArrayLength(jtab);
  printf("int [] : ["); 
  for (i = 0; i < len ; i++) printf("%d  ", tab[i]); 
  printf("]\n");
}


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]