In additional to solution 2, I can say following. In some cases conversion can be done easy with the ATL helper conversion macros which can be used inline:
W2A
,
A2W
and their variations. To use that macro you can call once in the view scope - for example at the beginning of the function or right before those macro usage another macro
USES_CONVERSION
. how that all work see in the next example:
USES_CONVERSION;
wchar_t wText[] = L" Unicode Text";
printf("ANSI: %s",W2A(wText));
TCHAR tText[] = _T("TCHAR Text");
printf("ANSI: %s",T2A(tText));
char aText[] = "MBCS Text";
_tcprintf(_T("TCHAR: %s"),A2T(aText));
Those macro allocate new string right in the stack which is freed while the function exist. I remember situation there I had stack overflow due that as those macro were used right in the main thread function loop, so keep that in mind.
Also in some other cases in additional to
WideCharToMultiByte
, or if you are not on Windows Platform you can use the function
wcstombs[
^] from the standard library.
And another option you can use the
sprintf[
^] /
swprintf[
^] functions with the string
"%S"
format, which means on Windows that passed argument should be converted depending to the function is used. For example if you use sprintf you can pass unicode text and if you use swprintf you can pass ansi text. See the next example:
char aText[100] = {0};
wchar_t wText[] = L"UNICODE Text";
sprintf(aText,"ANSI: %S",wText);
Regards,
Maxim