Form MSDN:
// convert_from_char.cpp
// compile with: /clr /link comsuppw.lib
#include
#include
#include
#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"
using namespace std;
using namespace System;
int main()
{
// Create and display a C style string, and then use it
// to create different kinds of strings.
char *orig = "Hello, World!";
cout << orig << " (char *)" << endl;
// newsize describes the length of the
// wchar_t string called wcstring in terms of the number
// of wide characters, not the number of bytes.
size_t newsize = strlen(orig) + 1;
// The following creates a buffer large enough to contain
// the exact number of characters in the original string
// in the new format. If you want to add more characters
// to the end of the string, increase the value of newsize
// to increase the size of the buffer.
wchar_t * wcstring = new wchar_t[newsize];
// Convert char* string to a wchar_t* string.
size_t convertedChars = 0;
mbstowcs_s(&convertedChars, wcstring, newsize, orig, _TRUNCATE);
// Display the result and indicate the type of string that it is.
wcout << wcstring << _T(" (wchar_t *)") << endl;
...
}
The definition oft TCHAR
is depending on whether you are using Unicode or ANSI.
See also here:
By using the Tchar.h, you can build single-byte, Multibyte Character Set (MBCS), and Unicode applications from the same sources.
Tchar.h defines macros (which have the prefix _tcs) that, with the correct preprocessor definitions, map to str, _mbs, or wcs functions, as appropriate. To build MBCS, define the symbol _MBCS. To build Unicode, define the symbol _UNICODE. To build a single-byte application, define neither (the default).
By default, _MBCS is defined for MFC applications.
The _TCHAR data type is defined conditionally in Tchar.h. If the symbol _UNICODE
is defined for your build, _TCHAR
is defined as wchar_t;
otherwise, for single-byte and MBCS builds, it is defined as char. (wchar_t, the basic Unicode wide-character data type, is the 16-bit counterpart to an 8-bit signed char.) For international applications, use the _tcs family of functions, which operate in _TCHAR units, not bytes. For example, _tcsncpy copies n _TCHARs, not n bytes.