When need to use FreeHGlobal()?
If I use Marshal::StringToHGlobalAnsi
as following:
char *src = (char *)Marshal::StringToHGlobalAnsi(this->Textbox1->Text).ToPointer();
Do I need to use Marshal::FreeHGl开发者_如何转开发obal()
? And if, What parameter should I give ?
According to MSDN - yes, you need to call FreeHGlobal. http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.stringtohglobalansi%28v=VS.100%29.aspx:
Because this method allocates the unmanaged memory required for a string, always free the memory by calling FreeHGlobal
The C# string conversion functions are absolutely horrible by C++ standards.
C++/CLI has its own string conversion helpers, which follow the rules of RAII to automatically clean up temporary buffers. Just use:
#include <stdlib.h>
#include <string.h>
#include <msclr\marshal.h>
using namespace msclr::interop;
marshal_context converter;
const char *src = converter.marshal_as<const char*>(Textbox1->Text);
Attach my 2 practice code for Marshal::FreeHGlobal Be noted that the argument of Marshal::FreeHGlobal() are different!!
string CPlusPlusString;
String ^VisualString;
VisualString=textBox1->Text;
CPlusPlusString=(char *)Marshal::StringToHGlobalAnsi(VisualString).ToPointer();
Marshal::FreeHGlobal(Marshal::StringToHGlobalAnsi(VisualString));
char *CString;
String ^VisualString;
VisualString=textBox1->Text;
CString = (char*) Marshal::StringToHGlobalAnsi(VisualString).ToPointer();
Marshal::FreeHGlobal(IntPtr(CString));
精彩评论