Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ CLI System.String^ to MFC LPCTSTR

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.

like image 868
Landin Martens Avatar asked Mar 20 '12 07:03

Landin Martens


2 Answers

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

like image 91
Amy Sutedja Avatar answered Sep 17 '22 17:09

Amy Sutedja


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.

like image 22
Botz3000 Avatar answered Sep 19 '22 17:09

Botz3000