After passing an object to a native method, how do you access its member variables if they are arrays of primitives?

Alexander Krapf

In Java, all arrays are objects. An array of characters is an Object and, in JNI, is represented as a jobject. Actually, JNI defines a jcharArray type to make usage a little bit more typesafe, but for all practical purposes you can say that you're dealing with jobjects.

When you get passed n object, you just have its jobject handle. Your native method then has to access the field through GetObjectField. Remember, arrays (even of primitives) are objects. You use the returned jobject as input to the primitive array manipulation methods Get<primitive type>ArrayRegion and Set<primitive type>ArrayRegion. You can query the length of the array through GetArrayLength.

This is one of the areas where JNI is pretty messy, especially once you go to arrays of arrays or arrays of objects.

A better alternative for you might be our JunC++ion product which generates C++ proxy classes for Java classes and comes with primitive array proxy classes already done. It allows you to implement a native method in C++ like this:

  //our native method declaration abbreviated
  void _cmj_Java_My_method( ..., const MyType & arg )
    jcpp_char_array  arr = arg.myArray;
    for( int i; i<arr.length; i++ )
      arr[ i ] = 'x'
You can find out more about JunC++ion at http://www.codemesh.com. It is generally available on Wintel but ports to various Unixes are underway.