anyone know of a quick way to convert the data in a char array to a unicode array? I have to support an existing application that will only pass the filename as a char array.
Printable View
anyone know of a quick way to convert the data in a char array to a unicode array? I have to support an existing application that will only pass the filename as a char array.
Sure. This should get you started:
Code:Strings::CStringExW AnsiToUTF16(const Strings::CStringExA& strFrom)
{
Strings::CStringExW strTo;
int nLen = MultiByteToWideChar(CP_ACP, 0, strFrom, -1, NULL, NULL);
MultiByteToWideChar(CP_ACP, 0, strFrom, -1, strTo.GetBuffer(nLen + 1), nLen);
strTo.ReleaseBuffer();
return strTo;
}
If you aren't using MBCS (which you probably aren't) then just use a for loop and assign each character.
The values for ASCII characters (0x00 - 0x7F) have the same values under Unicode.
If you are using MBCS, or some ansi code page with "special" character symbols being used (>0x7F) then you can use mbstowcs() or MultiByteToWideChar().
gg
Thanks code, once again you are the man :)
On a side note...
>> MultiByteToWideChar(CP_ACP, 0, strFrom, -1, strTo.GetBuffer(nLen + 1), nLen);
Check that return code!
Is it safe to run the following with your string class?
On a regular MFC CString, I don't think this is safe since the release will do some sort of strlen() on the buffer, which may of been freshly allocated and not null-terminated.Code:strTo.GetBuffer(20);
strTo.ReleaseBuffer();
Plus, who knows if MB2WC could bomb after writting characters but not the null-terminator.
gg
Yes, you're right. Much of the code lacks error handling and error checking.
And you're right that it isn't safe since it emulates CString behavior.
But thanks for the heads up. I'm going to look into the issue somewhat.