Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 重新解释与c风格的演员JNI_Java_C++_C_Casting_Java Native Interface - Fatal编程技术网

Java 重新解释与c风格的演员JNI

Java 重新解释与c风格的演员JNI,java,c++,c,casting,java-native-interface,Java,C++,C,Casting,Java Native Interface,在使用reinterpret_cast与C风格的cast时,我在使用JNI时遇到了一些非常奇怪的行为 如果我使用以下命令从Java调用函数: ArrayList<String> list = instance.tokenize("Я Я", "[\\w+0-9-_]+", 0x01); for (String str : list) { System.out.println(str); } 这正是我需要的输出 不过,作为C++ C++中的严格C++代码,我决定用重新解释的

在使用reinterpret_cast与C风格的cast时,我在使用JNI时遇到了一些非常奇怪的行为

如果我使用以下命令从Java调用函数:

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

for (String str : list) {
    System.out.println(str);
}
这正是我需要的输出

不过,作为C++ C++中的严格C++代码,我决定用重新解释的方式来代替我的C样式转换,尤其是前两个版本。 瞧那讨厌我的虫子。。它打印Я\nЯ\n寵.

那个亚洲人是从哪里来的?!这都是因为我把前两个C风格的演员阵容改成了重新诠释


为什么会发生这种情况?我尝试了静态强制转换,它显然不起作用。

你不应该使用jchar 16位类型作为wchar t大小不确定的类型,除非你确定什么是16位用于你的平台,并且你不关心可移植性。这也可能是你问题的根源。不确定是否有其他方法可以解决这一问题。。它不允许我使用:std::basic_regex而不是std::basic_regex又名std::wregex。你应该使用转换算法,而不是强制转换。是的,我刚读到它不以null终止字符串。你必须通过env->GetStringLengthbytes知道字符串的长度。你救了我!我没有注意到我使用了错误的长度函数。我调用的是env->GetStringUTFLength,而不是env->GetStringLength。这就解决了!非常感谢。
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;
}