i'm using this code to convert a String ^ in char *
String ^str = "string .net";
IntPtr p =
System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(str);
LPCSTR str2 = reinterpret_cast<LPCSTR>(static_cast<void *>(p));
System::Runtime::InteropServices::Marshal::FreeHGlobal(p);
I would like to make safe code, so i would like to use safe_cast
instead of reinterpret_cast or static_cast.
I tryed, but i can't achieve making something to work.
Do you have an idea ?
Thanks in advance for your help
Nicolas H.
> i'm using this code to convert a String ^ in char *
I use the following struct and code:
struct StringConvA
{
char *szAnsi;
StringConvA(System::String* s)
:
szAnsi(static_cast<char*>(System::Runtime::InteropServices::Marshal::String茅oHGlobalAnsi(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::范tringToHGlobalUni(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
http://blog.kalmbachnet.de/
Your method looks like mine, using static_cast.
I would rather user safe_cast, but this should not be possible ...
Regards,
Nicolas
If you compile with /clr:safe, you can not use pointers at all. If you use
/clr:pure or /clr, and encapsulate the ugly cast in a separate class that
also provides cleanup of the native data, you should be fine.
Marcus
<nicolas...@motorola.com> wrote in message
news:1145690597.8...@i39g2000cwa.googlegroups.com...
>If you compile with /clr:safe, you can not use pointers at all. If you use
>/clr:pure or /clr, and encapsulate the ugly cast in a separate class that
>also provides cleanup of the native data, you should be fine.
>Marcus
Yes, you're right Marcus, that's the good question :)
No need to make it safe or to get error messages exceptions
Thanks for your help
Nicolas H.
Yes, at least for the W-Version... for the A-Version you need to use
such a construct...