Basically I have a function that roughly looks like this and I need to return out.
const char* UTF16ToUTF8(const wchar_t *in) {
int tmp = wcslen(in);
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &in[0], (size_t)tmp, NULL, 0, NULL, NULL);
std::vector<char> out;
out.resize(size_needed);
WideCharToMultiByte(CP_UTF8, 0, &in[0], (size_t)tmp, &out[0], size_needed, NULL, NULL);
return &out[0];
}
Obviously out gets dereferenced when returning. What are my options? I need to be able to call this function like so. I would absolutely love to stay on the stack.
utf8outputfile << UTF16ToUTF8(wchar_tString) << endl;
fprintf(utf8outputfile, "%s", UTF16ToUTF8(L"Mmm Mmm Unicode String κόσμε"));
return UTF16ToUTF8(wchar_tString);
Don’t trouble yourself with any such worries and return an
std::string:Then, in your C interface, use:
I would even make the argument of the function
std::wstringand extract the C-string only when calling the API function.The
begin/endversion includes all characters, the.data()version treats the buffer as a null-terminated string. Pick whichever is most appropriate.