how to convert from managed string to char* in c++\clr ?

Posted on 2009-04-04
Last Modified: 2013-12-17
how to  convert from managed string to char* in c++\clr ?
here is my try below:
but it returns an error:
error C2682: cannot use 'safe_cast' to convert from ' System::String ^ '  to ' char * '

System::String^ s = "test";

	cascade_name = safe_cast<char*,System::String^>(s);

\\ Important note: cascade_name variable is a global variable which has type of char*

\\ from header file: char* cascade_name;

Open in new window

Question by:Ameerh24
LVL 86

Accepted Solution

jkr earned 350 total points
Comment Utility
Take a look at ("How to convert from System::String* to Char* in Visual C++ ") whichalso covers your problem (scroll down for the full code):
		     System::String ^ str = "Hello world\n";


	     //method 1

	     pin_ptr<const wchar_t> str1 = PtrToStringChars(str);



	     //method 2

	     char* str2 = (char*)Marshal::StringToHGlobalAnsi(str).ToPointer();




	     //method 3

	     CString str3(str); 



     	//method 4

#if _MSC_VER > 1499 // Visual C++ 2008 only

	     marshal_context ^ context = gcnew marshal_context();

	     const char* str4 = context->marshal_as<const char*>(str);


	     delete context;


Open in new window


Assisted Solution

mayank13 earned 150 total points
Comment Utility
Let say we have :

string s1 = "abcd";

char *c1;

Now to convert string to char just use strcpy() having ->

strcpy( c1, s1.c_str());

Note: s1.c_str(), tell compiler to read string as char* string.


Author Closing Comment

Comment Utility
thanks, the solution woks fine

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
In my previous two articles we discussed Binary Serialization ( and XML Serialization ( In this article we will try to know more about SOAP (Simple Object Acces…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now