How do I pass an array of primitives to a native method, like a char[]? And how do I define/access it from the C/C++ side?

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 a character array, your native method sees a jobject as an argument. You use that jobject as input to the primitive array manipulation methods GetCharArrayRegion and SetCharArrayRegion. 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( ..., jcpp_char_array & arr )
    for( int i; i<arr.length; i++ )
      arr[ i ] = 'x'
You can find out more about JunC++ion at It is generally available on Wintel but ports to various Unixes are underway.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact