“iconv”从UTF-32LE转换为UTF-16LE

时间:2018-01-08 12:21:05

标签: c++ macos encoding iconv

我最终正在为64位构建我的库,现在在Mac OS X,C ++ 64位上从UTF-32LE向UTF-16LE的转换失败。

在执行步骤之前,我的源是正确的字符串,执行iconv步骤会清除源和源大小。

iconv_t theHandle = NULL;
std::wstring source(L"My Source string to convert!");
size_t theSourceLength = source.length();
wchar_t *theSourceStart = (wchar_t*)source.c_str();
size_t sourceByteSize = sizeof(wchar_t)*theSourceLength;
UniChar* destination = new UniChar[ theSourceLength +2];
size_t destinationByteSize = sizeof(UniChar)*theSourceLength;
static const char *destinationEncoding = "UTF-16LE";
static const char *sourceEncoding = "UTF-32LE";
theHandle = iconv_open( destinationEncoding, sourceEncoding );
std::cout << "Conversion error: " << errno << std::endl;
if (errno == EINVAL)
    std::cout << "EINVAL" << std::endl;

size_t convertedSize = iconv( theHandle, (char**)&theSourceStart, &sourceByteSize, (char**)&destination, &destinationByteSize );
std::cout << "Conversion error: " << errno << std::endl;
if (errno == E2BIG)
    std::cout << "E2BIG" << std::endl;
if (errno == EILSEQ)
    std::cout << "EILSEQ" << std::endl;
if (errno == EINVAL)
    std::cout << "EINVAL" << std::endl;

当我在iconv行的调试器中停止时,“theSourceStart”显示为“我要转换的源字符串!”和sourceByteSize == 112,当我执行一步时,convertedSize == 0和theSourceStart == L“”,sourceByteSize == 0.

1 个答案:

答案 0 :(得分:0)

我错了,它按预期工作。我唯一错过的,因为我调试太深,缓冲区指针实际上由iconv运算符改变了,这就是为什么我的源字符串似乎是空的。但是,如果我保留原始指针,则正确填充目标中的值,并且源不受影响。所以我的申请有效。