Hi Joachim!
How to convert String^ (managed) to LPCTSTR (unmanaged)?
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::Interop Services::Marshal::StringÂ*ToHGlobalAnsi(s).ToPoin ter()))
{}
~StringConvA()
{
System::Runtime::InteropServices::Marshal::FreeHGl obal(IntPtr(szAnsi));
}
operator LPCSTR() const
{
return szAnsi;
}
};
struct StringConvW
{
wchar_t *szUnicode;
StringConvW(System::String^ s)
:
szUnicode(static_cast<wchar_t*>(System::Runtime::I nteropServices::Marshal::Â*StringToHGlobalUni(s).T oPointer()))
{}
~StringConvW()
{
System::Runtime::InteropServices::Marshal::FreeHGl obal(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
http://blog.kalmbachnet.de/