Article ID: 311259 - Last Review: April 1, 2008 - Revision: 5.0 How to convert from System::String* to Char* in Visual C++This article was previously published under Q311259 This article refers to the following
Microsoft .NET Framework Class Library namespaces:
On This PageSUMMARYThis article discusses several ways to convert from System::String* to char* by using the following:
Method 1PtrToStringChars gives you an interior pointer to the actual String object. If you pass this pointer to an unmanaged function call, you must first pin the pointer to ensure that the object does not move during an asynchronous garbage collection process:Method 2StringToHGlobalAnsi copies the contents of a managed String object into native heap, and then converts it into American National Standards Institute (ANSI) format on the fly. This method allocates the required native heap memory:
http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx
(http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx)
These steps apply to the whole article.
Method 3The VC7 CString class has a constructor that takes a managed String pointer and loads the CString with its contents:Method 4Visual C++ 2008 introduces the marshal_as<T> marshal help class and the marshal_context() marshal helper class.Note This code does not compile by using managed extensions for C++ in Visual C++ .NET 2002 or in Visual C++ .NET 2003. It uses the new C++/CLI syntax that was introduced in Visual C++ 2005 and the new msclr namespace code that was introduced in Visaul C++ 2008. To successfully compile this code, you must use the /clr C++ compiler switch in Microsoft Visual C++ 2008. Managed Extensions for C++ sample code (Visual C++ 2002 or Visual C++ 2003)C++/CLI sample code (Visual C++ 2005 and Visual C++ 2008)REFERENCES For other top-hit Visual C++ .NET Microsoft Knowledge Base
articles, visit the following Microsoft Web site: http://support.microsoft.com/default.aspx?xmlid=fh%3BEN-US%3Bvcnet
(http://support.microsoft.com/default.aspx?xmlid=fh%3ben-us%3bvcnet)
For more general information about Visual C++ .NET, visit the
following Microsoft Usenet newsgroup: Microsoft.public.dotnet.languages.vc
(http://msdn.microsoft.com/newsgroups/default.aspx?query=Microsoft.public.dotnet.languages.vc+&dg=&cat=en-us-msdn&lang=en&cr=US&pt=&catlist=774F24A2-F71F-425F-AC2B-DC48AB0DA5C9&dglist=&ptlist=&exp=&sloc=en-us)
| Article Translations
|

Back to the top
