Re: Marshal::StringToHGlobalAnsi and System.AccessViolationException

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance




"Mihai N." <nmihai_year_2000@xxxxxxxxx> wrote in message news:Xns9A51BD2DAA573MihaiN@xxxxxxxxxxxxxxxx

Leaving aside the fact that there are better ways to accomplish what I
want (like calling .ToPointer() for example)
If you know that is better, why not use it?

========================
String^ managedString = "Hello unmanaged world (from the managed world).";
char* stringPointer = (char*) Marshal::StringToHGlobalAnsi(managedString
).ToPointer();
Marshal::FreeHGlobal(IntPtr(stringPointer));

Don't cast and cast back. Instead:

IntPtr hglobalPtr = Marshal::StringToHGlobalAnsi(managedString);
char* stringPointer = static_cast<char*>(hglobalPtr.ToPointer());
....
Marshal::FreeHGlobal(hglobalPtr);




Official example at http://msdn2.microsoft.com/en-
us/library/system.runtime.interopservices.marshal.stringtohglobalansi.aspx
==================


LPCSTR str = static_cast<LPCTSTR>(const_cast<void*>(static_cast<const
Potential problem here: why static_cast to LPCTSTR if what you want is
LPCSTR? The 'T' in LPCTSTR means that when compiled as Unicode the type
is really wchar_t const *, while LPCSTR is char const *
So you basically do char const * str = static_cast<wchar_t const *>(...)


--
Mihai Nita [Microsoft MVP, Windows - SDK]
http://www.mihai-nita.net
------------------------------------------
Replace _year_ with _ to get the real email

.



Relevant Pages

  • Re: Marshal::StringToHGlobalAnsi and System.AccessViolationException
    ... want (like calling .ToPointer() for example) ... The 'T' in LPCTSTR means that when compiled as Unicode the type ... while LPCSTR is char const * ...
    (microsoft.public.dotnet.framework.interop)
  • Re: LPCSTR, Unicode etc... dont understand
    ... Use LPCTSTR instead of LPCSTR. ... LPCTSTR is a macro that means LPCSTR if UNICODE is undefined ... and LPCWSTR otherwise. ...
    (microsoft.public.windowsce.embedded.vc)
  • Re: Cant instantiate abstract class
    ... STDMETHOD(THIS_ LPCSTR Name, ... LPD3DXFRAME ... Name parameter is of type LPCSTR in the interface, but LPCTSTR in your ...
    (microsoft.public.vc.language)
  • Re: LPCTSTR and CString
    ... i have a extension dll with this functuon ... LPCTSTR lpcstr; ... IOW, it returns a dangling pointer, which is a fatal flaw. ... extern "C" LPCTSTR WINAPI TestString; ...
    (microsoft.public.vc.mfc)
  • Re: lpctstr in ellipsen, mal wieder vc6 vs. vc8
    ... es gibt ja LPCTSTR und LPCSTR. ... die aufrufe mit LPCTSTR klappen alle,die mit LPCSTR blöderweise nicht. ... wenn ich als formatzeichen allerdings %S oder %hs statt %s angebe, klappts mit LPCSTR und nicht mehr mit LPCTSTR ...
    (microsoft.public.de.vc)