Darth Ninja
Darth Ninja

Reputation: 1039

Extracting a string from JNI GetByteArrayElements call

To avoid the overhead of converting a byte[] to String, I am passing in the byte[] from Java to a native call. I use GetByteArrayElements to get access to the jbyte pointer and cast it to a (char *). At times, I see some non-ASCII characters printed using this approach.

After researching this, I understand this could happen if the java byte[] is not null terminated.

Question -

  1. What is the best way to extract the characters from JNI when dealing with a byte[]?

  2. On the java side, if I convert byte[] -> String -> byte[], will that add a null character at the end?

Upvotes: 0

Views: 984

Answers (1)

Sergei Bubenshchikov
Sergei Bubenshchikov

Reputation: 5371

While you create byte array from string you hold some memory. You can pass String directly and save memory.

Proper way of converting String (jstring in C++) to char* is:

JNIEXPORT jstring JNICALL Java_your_package_structure_className_myMethod(JNIEnv* env, jobject jobj, jstring str) {

    char* native_string = env->GetStringUTFChars(env, str, JNI_FALSE);

    const char* hello = "hello ";
    char* hello_prefix = new char[6 + strlen(native_string)];
    strcpy(hello_prefix, hello);
    strcat(hello_prefix, native_string);
    /*
    call
    env->ReleaseStringUTFChars(env, str, native_string);
    if env->GetStringUTFChars(env, str, JNI_TRUE) was executed
    */

    jstring result = env->NewStringUTF(env, hello_prefix);
    delete[] hello_prefix;

    return result;
}

const char* GetStringUTFChars(JNIEnv *env, jstring string, jboolean *isCopy);

Returns a pointer to an array of bytes representing the string in modified UTF-8 encoding. This array is valid until it is released by ReleaseStringUTFChars(). If isCopy is not NULL, then *isCopy is set to JNI_TRUE if a copy is made; or it is set to JNI_FALSE if no copy is made.

Critical natives

While you works with primitive types, you can use fast critical natives functions to reduce overhead of java conversions. Look at this post for details.

Upvotes: 1

Related Questions