cast System::String* to LPTSTR

  • Thread starter Thread starter Mark
  • Start date Start date
M

Mark

Help please... i am VERY new to the managed C++ and i need to take a
System::String* and cast it to an LPTSTR how might i do this? I have
searched the web and groups but cannot find any examples.

-thanks
 
i'll reply to myself since i found the answer...
System::String* Principals

LPTSTR secPrincipals =
(LPTSTR)System::Runtime::InteropServices::Marshal::StringToCoTaskMemAnsi(Pri
ncipals).ToInt32();
 
Also, if you just need a temporary pointer to it:

#include <vcclr.h>
System::String *managedString = new String("Hello");
const wchar_t __pin *unmanagedString = PtrToStringChars(managedString);

Note that since the returned string is const, you can't (and definitely
shouldn't) manipulate it. The __pin locks down the managed memory so the
memory manager doesn't move it around on you, and once the pointer goes out
of scope it's gone. Don't save a reference or anything like that. If you
need to save it or manipulate it, the method you came up with below is the
way to go. This suggestion is just more efficient if you only need to
"glance" at the string.

Brian
 
Mark said:
i'll reply to myself since i found the answer...
System::String* Principals

LPTSTR secPrincipals =
(LPTSTR)System::Runtime::InteropServices::Marshal::StringToCoTaskMemAns
i(Pri ncipals).ToInt32();

This will only work, if you have an ANSI build. For unicode-builds you have
to use the corresponding Uni-Version of the method (or for use
PtrToStringChars).


--
Greetings
Jochen

Do you need a memory-leak finder ?
http://www.codeproject.com/useritems/leakfinder.asp
 
For me the following conversation works to get LPTSTR from System::String to use in a thread creation process:

LPTSTR szCmdline= (LPTSTR)System::Runtime::InteropServices::Marshal::StringToHGlobalAuto(clc).ToInt32();
 
Back
Top