本文介绍了从utf8字符将jstring(JNI)转换为std :: string(c ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 jstring (JNI)转换为 std :: string (c ++) > utf8 个字符?

How to convert jstring (JNI) to std::string (c++) with utf8 characters?

这是我的代码。

std::string jstring2string(JNIEnv *env, jstring jStr){
    const char *cstr = env->GetStringUTFChars(jStr, NULL);
    std::string str = std::string(cstr);
    env->ReleaseStringUTFChars(jStr, str);
    return str;
}


推荐答案

经过很多时间后才找到解。我找到了一种方法:

After a lot time to find solution. i was found a way:

在Java中,Unicode字符将使用2个字节( utf16 )进行编码。因此 jstring 将包含字符 utf16 。 c ++中的 std :: string 本质上是一个字节字符串,而不是字符,因此,如果我们要从中传递 jstring JNI c ++ ,我们已经将 utf16 转换为字节。

In java, a unicode char will be encoded using 2 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.

在文档,我们有2个函数可从jstring中获取字符串:

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

GetStringUTFChars ,它将返回。

GetStringChars 将返回jbyte *,我们将从jbytes中读取char代码并将其转换为c ++中的char

GetStringChars will return jbyte *, we will read char code from jbytes and convert it to char in c++

this是我的解决方案(与 ascii utf8 字符配合良好):

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

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

    const jclass stringClass = env->GetObjectClass(jStr);
    const jmethodID getBytes = env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B");
    const jbyteArray stringJbytes = (jbyteArray) env->CallObjectMethod(jStr, getBytes, env->NewStringUTF("UTF-8"));

    size_t length = (size_t) env->GetArrayLength(stringJbytes);
    jbyte* pBytes = env->GetByteArrayElements(stringJbytes, NULL);

    std::string ret = std::string((char *)pBytes, length);
    env->ReleaseByteArrayElements(stringJbytes, pBytes, JNI_ABORT);

    env->DeleteLocalRef(stringJbytes);
    env->DeleteLocalRef(stringClass);
    return ret;
}

这篇关于从utf8字符将jstring(JNI)转换为std :: string(c ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 04:08