reinterpret_cast与c风格的演员JNI

时间:2014-02-10 01:21:19

标签: java c++ c casting java-native-interface

在使用reinterpret_castC-style casting时,我遇到了一些使用JNI的非常奇怪的行为。

如果我使用以下方法从Java调用我的函数:

ArrayList<String> list = instance.tokenize("Я Я", "[\\w+0-9-_]+", 0x01);

for (String str : list) {
    System.out.println(str);
}

打印Я \n Я使用C样式转换很好,如下所示(casting jchar* to wchar_t*)

extern "C" JNIEXPORT jobject Java_Native_tokenize(JNIEnv* env, jobject obj, jstring jquestion, jstring jregex, jint mode)
{
    const wchar_t* utf16question = (const wchar_t*)env->GetStringChars(jquestion, false);
    const wchar_t* utf16regex = (const wchar_t*)env->GetStringChars(jregex, false);

    std::wregex pattern(utf16regex, static_cast<std::regex::flag_type>(mode));
    auto itr_beg = std::regex_iterator<const wchar_t*>(utf16question, utf16question + env->GetStringUTFLength(jquestion), pattern);
    auto itr_end = std::regex_iterator<const wchar_t*>();

    jclass array_list_class = env->FindClass("Ljava/util/ArrayList;");
    jmethodID add_method = env->GetMethodID(array_list_class, "add", "(Ljava/lang/Object;)Z");
    jobject array_list = env->NewObject(array_list_class, env->GetMethodID(array_list_class, "<init>", "()V"));

    while (itr_beg != itr_end)
    {
        std::wstring wstr = itr_beg++->str();
        jstring str = env->NewString((jchar*)wstr.c_str(), wstr.size());
        env->CallVoidMethod(array_list, add_method, str);
    }

    env->ReleaseStringChars(jregex, (jchar*)utf16regex);
    env->ReleaseStringChars(jquestion, (jchar*)utf16question);
    return array_list;
}

这是我需要的确切输出..

然而,作为C ++中严格的C ++代码,我决定用reinterpret_cast替换我的C-Style演员(特别是前两个演员)。

看到令我讨厌的错误..它打印Я \n Я \n 寵

这个亚洲人物来自世界的哪个地方?!所有这些都是因为我将前两个C-Style演员阵容改为reinterpret_cast

出现这种情况的原因是什么?我试过了static_cast,它显然无效。

0 个答案:

没有答案