Wednesday, April 24, 2013

jni jnienv SetObjectArrayElement example c c++ java


SetObjectArrayElement


void SetObjectArrayElement(JNIEnv *env, jobjectArray array,
jsize index, jobject value);

Sets an element of an Object array.
LINKAGE:
Index 174 in the JNIEnv interface function table.
PARAMETERS of SetObjectArrayElement

env: the JNI interface pointer.

array: a Java array.

index: array index.

value: the new value.

THROWS of SetObjectArrayElement

ArrayIndexOutOfBoundsException: if index does not specify a valid index in the array.

ArrayStoreException: if the class of value is not a subclass of the element class of the array.
Example of SetObjectArrayElement


Main.java
public class Main {

    static {
        System.loadLibrary("mynative");
    }

    private static native String[][] getStringArrays();

    public static void main(String[] args) {
        for (String[]  array : getStringArrays())
            for (String s : array)
                System.out.println(s);
    }
}
mynative.c
static jobjectArray make_row(JNIEnv *env, jsize count, const char* elements[])
{
    jclass stringClass = (*env)->FindClass(env, "java/lang/String");
    jobjectArray row = (*env)->NewObjectArray(env, count, stringClass, 0);
    jsize i;

    for (i = 0; i < count; ++i) {
        (*env)->SetObjectArrayElement(env, row, i, (*env)->NewStringUTF(env, elements[i]));
    }
    return row;
}

JNIEXPORT jobjectArray JNICALL Java_Main_getStringArrays(JNIEnv *env, jclass klass)
{
    const jsize NumColumns = 4;
    const jsize NumRows = 2;

    const char* beatles[] = { "John", "Paul", "George", "Ringo" };
    jobjectArray jbeatles = make_row(env, NumColumns, beatles);

    const char* turtles[] = { "Leonardo", "Raphael", "Michaelangelo", "Donatello" };
    jobjectArray jturtles = make_row(env, NumColumns, turtles);

    jobjectArray rows = (*env)->NewObjectArray(env, NumRows, (*env)->GetObjectClass(env, jbeatles), 0);

    (*env)->SetObjectArrayElement(env, rows, 0, jbeatles);
    (*env)->SetObjectArrayElement(env, rows, 1, jturtles);
    return rows;
}