Skip to content
Search

JNI:DataByPass

lastmod 2018-08-17created 2016-06-212 edits

Explains how to pass data between JAVA and JNI.

How to pass a Java array type

Explains how to obtain array-type data from JAVA in JNI. The Method Prototype for the JNI call on the JAVA side is as follows.

private static native void generateTexture(int [] pixels);

The Method implementation on the JNI side is as follows.

JNIEXPORT void JNICALL
Java_com_example_MapView_generateTexture(JNIEnv* env, jobject thiz, jintArray pixels)
{
    int * acquire_pixels = env->GetIntArrayElements(pixels, 0);
    if (acquire_pixels != 0) {
        // use acquire_pixels.
    }
    env->ReleaseIntArrayElements(pixels, acquire_pixels, JNI_ABORT);
}

How to pass a Java String

Explains how to pass a String type from JAVA to JNI or receive one from it. The Method Prototype for the JNI call on the JAVA side is as follows.

public native String greeting(String name);

The Method implementation on the JNI side is as follows. It takes a string as input and returns it again.

JNIEXPORT jstring JNICALL
Java_JNITest_greeting(JNIEnv *env, jobject obj, jstring jstr) {
    const char *name = (*env)->GetStringUTFChars(env, jstr, NULL);//Java String to C Style string
    char msg[60] = "Hello ";
    jstring result;
    strcat(msg, name);
    (*env)->ReleaseStringUTFChars(env, jstr, name);
    puts(msg);
    result = (*env)->NewStringUTF(env, msg); // C style string to Java String
    return result;
}

How to pass a Java String 02

A simpler sample for passing a String type from JAVA to JNI is as follows.

JNIEXPORT void JNICALL
Java_com_example_MapView_generateTexture(JNIEnv* env, jobject thiz, jstring key)
{
    std::string key_string;
    const char * acquire_key = env->GetStringUTFChars(key, NULL);  //Java String to C Style string
    key_string.assign(acquire_key);
    env->ReleaseStringUTFChars(key, acquire_key);
}

See also