Skip to content

Instantly share code, notes, and snippets.

@thaenor
Created December 16, 2014 09:36
Show Gist options
  • Save thaenor/72b42e3e06063c927fe4 to your computer and use it in GitHub Desktop.
Save thaenor/72b42e3e06063c927fe4 to your computer and use it in GitHub Desktop.
Some stuff about converting strings to wide chars
// convert_from_char.cpp
// compile with: /clr /link comsuppw.lib
#include <iostream>
#include <stdlib.h>
#include <string>
#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;
// Convert the C style string to a _bstr_t string.
_bstr_t bstrt(orig);
// Append the type of string to the new string
// and then display the result.
bstrt += " (_bstr_t)";
cout << bstrt << endl;
// Convert the C style string to a CComBSTR string.
CComBSTR ccombstr(orig);
if (ccombstr.Append(_T(" (CComBSTR)")) == S_OK)
{
CW2A printstr(ccombstr);
cout << printstr << endl;
}
// Convert the C style string to a CstringA and display it.
CStringA cstringa(orig);
cstringa += " (CStringA)";
cout << cstringa << endl;
// Convert the C style string to a CStringW and display it.
CStringW cstring(orig);
cstring += " (CStringW)";
// To display a CStringW correctly, use wcout and cast cstring
// to (LPCTSTR).
wcout << (LPCTSTR)cstring << endl;
// Convert the C style string to a basic_string and display it.
string basicstring(orig);
basicstring += " (basic_string)";
cout << basicstring << endl;
// Convert the C style string to a System::String and display it.
String ^systemstring = gcnew String(orig);
systemstring += " (System::String)";
Console::WriteLine("{0}", systemstring);
delete systemstring;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment