11

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.

gideon
  • 19,329
  • 11
  • 72
  • 113
Landin Martens
  • 3,283
  • 12
  • 43
  • 61
  • 1
    note that LPCTSTR is just a char pointer, so maybe you'd rather convert String to CString or std::string and then obtain the pointer so you don't have to deal with memory managment – stijn Mar 20 '12 at 07:32

2 Answers2

17

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

Amy Sutedja
  • 432
  • 2
  • 9
  • Why not use LPCTSTR tstr = context.marshal_as< const TCHAR* >( cliString) and let the build environment take care of the actual string type? – TeaWolf Mar 20 '12 at 08:27
  • I've taken you up on your sensible idea, which for some reason had slipped my mind. Thanks! – Amy Sutedja Mar 20 '12 at 08:32
  • What's the difference between this marshal compared to the marshal in the other answer? – Stijn Tallon Dec 13 '14 at 20:22
  • Besides better semantics, using `marshal_context` means that the allocated string is destroyed when the context is destroyed. Calling `Marshal::StringToHGlobalAuto`, on the other hand, requires you to `FreeHGlobal` the returned string. – Amy Sutedja Dec 16 '14 at 01:08
3

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.

Botz3000
  • 39,020
  • 8
  • 103
  • 127