Search code examples
javac++arrayscastingjava-native-interface

Java - JNI - Casting UCS-2 character to jchar (i.e Java's char)


I want to transfer an array of "wide" characters from native C++ code to Java code. For this I have a natively implemented Java method :

public native char[] getRawText();

In the C++, I have a contiguous buffer of uchar16_t (actually 2 bytes wide unsigned integers). I would like to copy the contents of that buffer into the Java char array to be returned.

Is it safe to do the following :

// Buffer of uchar16_t characters (UCS-2 encoded unicode).
const uchar16_t * const wsRawText = /* Get it from native code */
// Length of that buffer
const uint32_t nLength = /* Same */

// Allocate the Java char array to be returned.
jcharArray pCharArray = pEnv->NewCharArray( nLength );
// Set the array elements, casting const uchar16_t * to const jchar *
pEnv->SetCharArrayRegion( pCharArray, 0, nLength, wsRawText );

return pCharArray;

Is it Ok to cast const uchar16_t * to const jchar * ?

The char array will be about 2000 characters long most of the time, so i would like to avoid useless copies.

I omitted the exception checking to keep the code simple.

Thank you.


Solution

  • jchar is define in jhi.h as:

    typedef unsigned short     jchar;
    

    If you are trying to return a string to java, take a look ant the JNI function NewStringUTF() which takes a C string and returns a java string

    NewStringUTF