C++ CLI System.String^ to MFC LPCTSTR
12,248
Solution 1
If you have Visual Studio 2008 or above, you should be able to do this using the C++/CLI marshaling library, like so:
#include <msclr\marshal.h>
using namespace System;
using namespace msclr::interop;
...
String^ cliString;
marshal_context context;
LPCTSTR cstr = context.marshal_as<const TCHAR*>(cliString);
More information on marshaling between types on MSDN: Overview of Marshaling in C++
Solution 2
You might want to try Marshal::StringToHGlobalUni, Marshal::StringToHGlobalAuto or Marshal::StringToHGlobalAnsi.
Remember the allocated unmanaged strings will need to be freed with Marshal::FreeHGlobal.
Author by
Landin Martens
Updated on June 20, 2022Comments
-
Landin Martens almost 2 years
How would I convert a System (.net)
C++\CLI
String^
into a MFC C++LPCTSTR
string.It is very easy to get a
LPCTSTR
intoString^
, but so far found nothing on doing it the other way around. -
TeaWolf about 12 yearsWhy not use LPCTSTR tstr = context.marshal_as< const TCHAR* >( cliString) and let the build environment take care of the actual string type?
-
Amy Sutedja about 12 yearsI've taken you up on your sensible idea, which for some reason had slipped my mind. Thanks!
-
Stijn Tallon over 9 yearsWhat's the difference between this marshal compared to the marshal in the other answer?
-
Amy Sutedja over 9 yearsBesides better semantics, using
marshal_context
means that the allocated string is destroyed when the context is destroyed. CallingMarshal::StringToHGlobalAuto
, on the other hand, requires you toFreeHGlobal
the returned string.