Wednesday, April 24, 2013

jni jnienv NewCharArray example c c++ java


New<PrimitiveType>Array Routines - NewCharArray


ArrayType New<PrimitiveType>Array(JNIEnv *env, jsize length);

A family of operations used to construct a new primitive array object. Table 4-8 describes the specific primitive array constructors. You should replace New<PrimitiveType>Array with one of the actual primitive array constructor routine names from the following table, and replace ArrayType with the corresponding array type for that routine.

Table 4-8a New<PrimitiveType>Array Family of Array Constructors

New<PrimitiveType>Array Routines

Array Type

NewBooleanArray()

jbooleanArray

NewByteArray()

jbyteArray

NewCharArray()

jcharArray

NewShortArray()

jshortArray

NewIntArray()

jintArray

NewLongArray()

jlongArray

NewFloatArray()

jfloatArray

NewDoubleArray()

jdoubleArray
LINKAGE:
Indices in the JNIEnv interface function table.
Table 4-8b New<PrimitiveType>Array Family of Array Constructors
New<PrimitiveType>Array Routines
Index
NewBooleanArray()
175
NewByteArray()
176
NewCharArray()
177
NewShortArray()
178
NewIntArray()
179
NewLongArray()
180
NewFloatArray()
181
NewDoubleArray()
182
PARAMETERS of NewCharArray

env: the JNI interface pointer.

length: the array length.

RETURNS of NewCharArray

Returns a Java array, or NULL if the array cannot be constructed.
Example of NewCharArray

In Java layer: in my native class I have following methods:
//Native method
public native String getStrData(int size);

//Callback method
public void addData(char[] native_data, int size) {

    ...

}
In Native layer: in my native implementation:
JNIEXPORT jstring JNICALL Java_com_pkg_NativeClass_getStrData 
   (JNIEnv *env, jobject obj, jint size) {
     ...

     jclass native_class;           /* Callback: native class */
     jmethodID native_method_id;    /* Callback: native method id */
     jcharArray row;                /* Callback: native data */

     ...

    /* Start Callback: Native to Java  */   
    native_class = (*env)->GetObjectClass(env, obj);
    native_method_id = (*env)->GetMethodID(env, native_class, "addData", "([CI)V");
    if (native_method_id == 0) {
        return (jstring)ERR_NATIVE_METHODID;
    }
    row = (jcharArray)(*env)->NewCharArray(env, size);
    /* jc has the data to be sent to Java */
    (*env)->SetCharArrayRegion(env, (jcharArray)row, (jsize)0, size, (jchar *)jc);

    (*env)->CallVoidMethod(env, obj, native_method_id, row, size);
    /* End Callback */

     ...
}