Create, populate, and return a 2D String array from native code (JNI / NDK)

I find this particular bit of code rather complicated (not least because I just started playing with C a week ago).

I tried to find the correct syntax to correctly create an array of java strings in C (i.e. an array of jstring objects, i.e. an object representing an array of jstring objects). I used the following resources, and from them I created code that compiles. I am not sure if the error that occurred after this occurred due to incorrect syntax or due to a completely separate reason. Since the code is mostly isolated, I assume the syntax is incorrect.

( Suns Programming Documentation and Suns JNI Documentation )

The code compiles, but after sending the line of code "FindClass", a SIGSEGV signal is sent, which kills the C process:

jint size = 5;
jclass StringObject = (*env)->FindClass(env, "java/lang/String");
jobjectArray sampleMessage = (*env)->NewObjectArray(env, size, StringObject, NULL);
jobjectArray returnArray = (jobjectArray) (*env)->NewObjectArray(env, messageCount, &sampleMessage, 0);

Can someone point me to a useful resource? Or confirm the syntax is correct.

EDIT

Most of my problem was that debugging this code caused the problem. I don’t have time to narrow down the reproducing factor, but it does NOT WORK to step over the JNI code in the gdb client through eclipse.

+3
source share
1 answer

To get jclass for a string type, you can call GetObjectClass()on one of the lines. It works:

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;
}

Construction, error handling omitted for clarity.

+16
source

All Articles