Select the product you need help with
- Internet Explorer
- Windows Phone
- More products
How to convert from System::String* to Char* in Visual C++
Article ID: 311259 - View products that this article applies to.
This article was previously published under Q311259
This article refers to the following Microsoft .NET Framework Class Library namespaces:
This 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:
Note In Visual C++ 2005 and in Visual C++ 2008, you must add the common language runtime support compiler option (/clr:oldSyntax) to successfully compile the previous code sample. To add the common language runtime support compiler option, follow these steps:
http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspxThese 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)
For other top-hit Visual C++ .NET Microsoft Knowledge Base articles, visit the following Microsoft Web site:
Article ID: 311259 - Last Review: October 15, 2012 - Revision: 6.0