lundi 23 janvier 2017

Share: JNI jstring to std::string for any people need

I was spend a lot times to find how to convert jstring to utf8 std::string in c++, so i want to share to somebody need to converter like me..

in java, a unicode char will be encoded with 4 bytes (utf16). so jstring will container characters utf16. std::string in c++ is essentially a string of bytes, not characters, so if we want to pass jstring from JNI to c++, we have convert utf16 to bytes.

in document JNI functions, we have 2 functions to get string from jstring:

// Returns a pointer to the array of Unicode characters of the string. 
// This pointer is valid until ReleaseStringchars() is called.
const jchar * GetStringChars(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().
const char * GetStringUTFChars(JNIEnv *env, jstring string, jboolean *isCopy);

if we are use GetStringUTFChars, it will return a modified utf8. That is not good, because it is not standard utf8.

The solution is use GetStringChars.

this is my solution (worked well with ascii and utf8 characters):

std::string jstring2string(JNIEnv *env, jstring jStr) {
    if (!jStr)
        return "";

    std::vector<char> charsCode;
    const jchar *chars = env->GetStringChars(jStr, NULL);
    jsize len = env->GetStringLength(jStr);
    jsize i;

    for( i=0;i<len; i++){
        int code = (int)chars[i];
        charsCode.push_back( code );
    }
    env->ReleaseStringChars(jStr, chars);

    return  std::string(charsCode.begin(), charsCode.end());
}

Hope it can help someone.

Aucun commentaire:

Enregistrer un commentaire