简体   繁体   English

使用iconv从C ++ UTF8到UTF16 Linux

[英]C++ UTF8 to UTF16 Linux using iconv

I am working with a vendor that is running on Windows and expects text in UTF16. 我正在与在Windows上运行的供应商合作,期望在UTF16中输入文本。 I'm running on Linux and it's UTF8. 我在Linux上运行,它是UTF8。 I'm trying to use iconv to convert from UTF8 to UTF16 so I can send over a socket connection. 我正在尝试使用iconv从UTF8转换为UTF16,以便可以通过套接字连接发送。 I found an article here stackOverflow , and tried to follow that code but nothing is returned from my function. 我在这里stackOverflow上找到了一篇文章,并尝试遵循该代码,但是我的函数未返回任何内容。 Has anyone had any experience converting from UTF-8 to UTF-16? 有没有人有从UTF-8转换为UTF-16的经验? thanks. 谢谢。

char * Convert( char *from_charset, char *to_charset, char *input )
{
size_t input_size, output_size, bytes_converted;
char * output;
char * tmp;
iconv_t cd;

cd = iconv_open( to_charset, from_charset);
if ( cd == (iconv_t) -1 )
{
    //Something went wrong with iconv_open
    if (errno == EINVAL)
    {
        char * buffer;
        sprintf(buffer, "Conversion from %s to %s not available", from_charset, to_charset);
        cout << buffer << endl;
    }
    return NULL;
}

input_size = strlen(input);
output_size = 2 * input_size;
output = (char*) malloc(output_size+1);

bytes_converted = iconv(cd, &input, &input_size, &output, &output_size);
cout << "Bytes converted: " << bytes_converted << endl;
if ( iconv_close (cd) != 0)
    cout<< "Error closing iconv_error" << endl;

return output;

} }

the iconv function takes the address of the pointers to strings and as it s converting it points to the next element of the char array. iconv函数将指针的地址指向字符串,并在转换时将其指向char数组的下一个元素。 when it finish the output actually points to the last element of the array , it can be null or something else. 完成输出后,它实际上指向数组的最后一个元素,可以为null或其他形式。 you need to save the starting address of the output string in a temp location . 您需要将输出字符串的起始地址保存在临时位置。 before feeding output to iconv do the following char * tempoutput = output ; 在将输出馈给iconv之前,请执行以下char * tempoutput = output;

and then after iconv call return tempoutput; 然后在iconv调用之后返回tempoutput;

and dont forget to free(output) and the returned string is also presistent you need to free it after using convert. 并且不要忘记释放(输出),返回的字符串也仍然存在,您需要在使用convert之后释放它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM