【发布时间】:2011-11-25 17:36:23
【问题描述】:
我在 unix 中将 wstring 转换为 jstring 时遇到问题,因为 linux 上 wchar_t 的大小为 4 个字节(不像 windows 那样为 2 个字节,因此我不能使用 wchar_t 到 jchar 的转换)。
谁能帮帮我?
谢谢, 雷扎
【问题讨论】:
标签: java c++ java-native-interface widestring
我在 unix 中将 wstring 转换为 jstring 时遇到问题,因为 linux 上 wchar_t 的大小为 4 个字节(不像 windows 那样为 2 个字节,因此我不能使用 wchar_t 到 jchar 的转换)。
谁能帮帮我?
谢谢, 雷扎
【问题讨论】:
标签: java c++ java-native-interface widestring
您必须使用iconv() 之类的东西,因为 C++ 宽字符串具有不透明(读取:未知)编码,而 Java 需要 UTF16。试试这个:
#include <iconv.h>
#include <string>
#include <vector>
#include <iostream>
std::u16string convert(std::wstring s)
{
iconv_t cd = iconv_open("UTF-16BE", "WCHAR_T");
if (cd == iconv_t(-1))
{
std::cout << "Error while initializing iconv: " << errno << std::endl;
iconv_close(cd);
return std::u16string();
}
std::size_t n = s.length() * 2 + 1; // Each character might use up to two CUs.
const std::size_t norig = n;
std::size_t m = s.length() * sizeof(std::wstring::value_type);
std::vector<char16_t> obuf(n);
char * outbuf = reinterpret_cast<char*>(obuf.data());
const char * inbuf = reinterpret_cast<const char*>(&s[0]);
const std::size_t ir = iconv(cd, const_cast<char**>(&inbuf), &m, &outbuf, &n);
if (ir == std::size_t(-1))
{
std::cout << "Error while converting with iconv(): " << errno << ":" << EINVAL << ", left " << m
<< ", written " << std::dec << norig - n << " bytes." << std::endl;
iconv_close(cd);
return std::u16string();
}
iconv_close(cd);
return std::u16string(obuf.data(), (norig - n)/sizeof(std::u16string::value_type));
}
如果您没有char16_t 和std::u16string,您可以使用uint16_t 作为基本字符类型,并使用std::basic_string<uint16_t> 或std::vector<uint16_t> 作为结果容器。
【讨论】:
u16string 是 C++11 标准的一部分。如果你不支持,你可以使用uint16_ts 的向量,正如我在最后一段中建议的那样。