Re: How to convert const char * to wchar_t
"Manni" <manujsabarwal@gmail.com> ha scritto nel messaggio
news:1c420830-306c-4435-aa12-c7751db9ef07@p10g2000prm.googlegroups.com...
How can I convert const char * to wchar_t?
Example: char *argv[] is my array and i want it to pass to different
file which accept only WCHAR **argv where WCHAR is defined as typedef
wchar_t WCHAR
To convert from char* (ANSI/MBCS) strings to wchar_t* (Unicode UTF-16)
strings, you could use CStringW constructor overload, or CA2W helper class,
or the "raw" Win32 API ::MultiByteToWideChar.
Here is a sample compilable code that shows you a possible way to convert
from char** argv to a WCHAR** 'argv':
<code>
//////////////////////////////////////////////////////////////////////////
// test1.cpp
#include <iostream> // Console output
#include <vector> // Vector container
#include <atlstr.h> // CStringW
using std::cout;
using std::wcout;
using std::endl;
//
// Prints strings stored in argv
//
void TestUnicodeArgv( WCHAR **argv )
{
wcout << endl;
wcout << "*** Unicode strings:" << endl;
WCHAR ** p = argv;
while ( *p != NULL )
{
wcout << *p << endl;
++p;
}
wcout << "----------" << endl;
}
//
// MAIN
//
int main(int argc, char * argv[])
{
//
// Convert strings from ANSI/MBCS
// to Unicode UTF16, storing them in a vector container
//
std::vector< CStringW > unicodeStrings;
unicodeStrings.reserve( argc );
for ( int i = 0; i < argc; i++ )
{
unicodeStrings.push_back( CStringW( argv[i] ) );
}
//
// Build an array of pointers to Unicode strings,
// NULL terminated
//
const int count = argc;
std::vector< WCHAR * > unicodeStringPtrs;
unicodeStringPtrs.reserve( count + 1 );
for (int i = 0; i < count; i++)
{
unicodeStringPtrs.push_back( const_cast<WCHAR
*>(unicodeStrings[i].GetString()) );
}
// Terminate with NULL
unicodeStringPtrs.push_back( NULL );
// Call the test function
TestUnicodeArgv( &unicodeStringPtrs[0] );
return 0;
}
</code>
HTH,
Giovanni