C++ CLI System.String^ to MFC LPCTSTR

Landin Martens picture Landin Martens · Mar 20, 2012 · Viewed 12.3k times · Source

How would I convert a System (.net) C++\CLI String^ into a MFC C++ LPCTSTR string.

It is very easy to get a LPCTSTR into String^, but so far found nothing on doing it the other way around.

Answer

Amy Sutedja picture Amy Sutedja · Mar 20, 2012

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++