How to convert ushort utf16 array to utf8 std :: string?

I am currently writing a plugin that is only a wrapper around an existing library. The host plugin passes me a utf-16 formatted string, defined as the following

typedef unsigned short PA_Unichar;

And the wrapped library only accepts a formatted string const char * or std :: string utf-8 I tried to write a conversion function like

std::string toUtf8(const PA_Unichar* data) { std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert; return std::string(convert.to_bytes(static_cast<const char16_t*>(data)); } 

But obviously this will not work, throwing me into the compilation error "static_cast from" const pointer "(aka 'const unsigned short *') to 'const char16_t *' is not allowed

What is the most elegant / correct way to do this?

Thanks in advance.

+6
source share
1 answer

You can convert the PA_unichar string to a char16_t string using the basic_string(Iterator, Iterator) constructor basic_string(Iterator, Iterator) , and then use the std::codecvt_utf8_utf16 facet as you tried:

 std::string conv(const PA_unichar* str, size_t len) { std::u16string s(str, str+len); std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert; return convert.to_bytes(s); } 

I think that's right. Unfortunately, I cannot verify this, since my implementation does not yet support it. I have a wstring_convert implementation that I plan to include in GCC 4.9, but I don't have a codecvt_utf8_utf16 implementation to test it.

+2
source

All Articles