开发者

When need to use FreeHGlobal()?

开发者 https://www.devze.com 2023-04-11 07:31 出处:网络
If I use Marshal::StringToHGlobalAnsi as following: char *src = (char *)Marshal::StringToHGlobalAnsi(this->Textbox1->Text).ToPointer();

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));
0

精彩评论

暂无评论...
验证码 换一张
取 消