Groups | Blog | Home
all groups > visual c > march 2007 >

visual c : String^ to LPCTSTR


Joachim
3/5/2007 7:02:13 AM
William DePalo [MVP VC++]
3/5/2007 11:35:58 AM
[quoted text, click to view]

You can check on the usage of PtrToStringChars() here:

http://blogs.msdn.com/slippman/archive/2004/06/02/147090.aspx

Regards,
Will
www.ivrforbeginners.com

Jochen Kalmbach [MVP]
3/5/2007 9:03:03 PM
Hi Joachim!

[quoted text, click to view]

See: How to convert from System::String* to Char* in Visual C++ 2005 or
in Visual C++ .NET
http://support.microsoft.com/kb/311259/en-us

The "easysed to use" function is

struct StringConvA
{
char *szAnsi;
StringConvA(System::String* s)
:
szAnsi(static_cast<char*>(System::Runtime::InteropServices::Marshal::String­ToHGlobalAnsi(s).ToPointer()))

{}
~StringConvA()
{


System::Runtime::InteropServices::Marshal::FreeHGlobal(IntPtr(szAnsi));
}
operator LPCSTR() const
{
return szAnsi;
}



};


struct StringConvW
{
wchar_t *szUnicode;
StringConvW(System::String* s)
:
szUnicode(static_cast<wchar_t*>(System::Runtime::InteropServices::Marshal::­StringToHGlobalUni(s).ToPointer()))

{}
~StringConvW()
{

System::Runtime::InteropServices::Marshal::FreeHGlobal(IntPtr(szUnicode));
}
operator LPCWSTR() const
{
return szUnicode;
}



};


#ifdef _UNICODE
#define StringConvT StringConvW
#else
#define StringConvT StringConvA
#endif

int _tmain()
{
String *s = S"abc";
std::string ansi = StringConvA(s);
std::wstring unicode = StringConvW(s);
_tprintf(_T("%s"), (LPCTSTR) StringConvT(s));


}

--
Greetings
Jochen

My blog about Win32 and .NET
Jochen Kalmbach [MVP]
3/5/2007 9:08:57 PM
Hi Joachim!

[quoted text, click to view]

Upps the last post was for managed C++... so here for C++/CLI:

#include <windows.h>
#include <tchar.h>
#include <string>
using namespace System;
struct StringConvA
{
char *szAnsi;
StringConvA(System::String ^s)
:
szAnsi(static_cast<char*>(System::Runtime::InteropServices::Marshal::String­ToHGlobalAnsi(s).ToPointer()))

{}
~StringConvA()
{
System::Runtime::InteropServices::Marshal::FreeHGlobal(IntPtr(szAnsi));
}
operator LPCSTR() const
{
return szAnsi;
}
};


struct StringConvW
{
wchar_t *szUnicode;
StringConvW(System::String^ s)
:
szUnicode(static_cast<wchar_t*>(System::Runtime::InteropServices::Marshal::­StringToHGlobalUni(s).ToPointer()))

{}
~StringConvW()
{
System::Runtime::InteropServices::Marshal::FreeHGlobal(IntPtr(szUnicode));
}
operator LPCWSTR() const
{
return szUnicode;
}
};

#ifdef _UNICODE
#define StringConvT StringConvW
#else
#define StringConvT StringConvA
#endif

int _tmain()
{
String ^s = "abc";
std::string ansi = StringConvA(s);
std::wstring unicode = StringConvW(s);
_tprintf(_T("%s"), (LPCTSTR) StringConvT(s));
}


--
Greetings
Jochen

My blog about Win32 and .NET
AddThis Social Bookmark Button