Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
utf8string2wstring.cpp
#include <iconv.h>
#include <string>
int convert(string input, wstring &output)
{
char *inbuf, *iptr, *outbuf, *wptr;
iconv_t cd;
size_t nconv, inlen, avail;
cd = iconv_open("UCS-4-INTERNAL", "UTF-8");
if (cd == (iconv_t)-1)
{
perror("iconv error");
return -1;
}
iptr = inbuf = strdup(input.c_str());
inlen = input.size();
avail = inlen * 4 + 1;
wptr = outbuf = (char*)calloc(avail * sizeof(char), 1);
nconv = iconv(cd, &iptr, &inlen, &wptr, &avail);
if (nconv == (size_t)-1)
{
perror("iconv error");
free(inbuf);
free(outbuf);
return -1;
}
iconv(cd, NULL, NULL, &wptr, &avail);
if (avail >= sizeof(char))
{
*wptr = '\0';
}
else
{
perror("iconv error");
free(inbuf);
free(outbuf);
return -1;
}
if (iconv_close(cd) != 0)
{
perror("iconv error");
free(inbuf);
free(outbuf);
return -1;
}
wchar_t *wstr = reinterpret_cast<wchar_t*>(outbuf);
output = wstring(wstr);
free(outbuf);
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.