jstring std::string互转
2021-01-30 本文已影响0人
CentForever
#include <string>
#include <locale>
#include <codecvt>
static std::string UTF16StringToUTF8String(const char16_t* chars, size_t len) {
std::u16string u16_string(chars, len);
return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}
.to_bytes(u16_string);
}
std::string JavaStringToString(JNIEnv* env, jstring str) {
if (env == nullptr || str == nullptr) {
return "";
}
const jchar* chars = env->GetStringChars(str, NULL);
if (chars == nullptr) {
return "";
}
std::string u8_string = UTF16StringToUTF8String(
reinterpret_cast<const char16_t*>(chars), env->GetStringLength(str));
env->ReleaseStringChars(str, chars);
return u8_string;
}
static std::u16string UTF8StringToUTF16String(const std::string& string) {
return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}
.from_bytes(string);
}
jstring StringToJavaString(JNIEnv* env,
const std::string& u8_string) {
std::u16string u16_string = UTF8StringToUTF16String(u8_string);
auto result =env->NewString(reinterpret_cast<const jchar*>(u16_string.data()),
u16_string.length());
return result;
}