3

如果我有多个本机类型变量,例如:

EmpNameC =( wchar_t *)Marshal::StringToHGlobalUni(this->textBox38->Text).ToPointer();
PyrllC =( wchar_t *)Marshal::StringToHGlobalUni(this->textBox31->Text).ToPointer();
DtbrthC=( wchar_t *)Marshal::StringToHGlobalUni(this->textBox37->Text).ToPointer();
PlcBrthC=( wchar_t *)Marshal::StringToHGlobalUni(this->textBox36->Text).ToPointer();
CIDC    =( wchar_t *)Marshal::StringToHGlobalUni(this->textBox35->Text).ToPointer();
ContNoC=( wchar_t *)Marshal::StringToHGlobalUni(this->textBox34->Text).ToPointer();
JndtC   =( wchar_t *)Marshal::StringToHGlobalUni(this->textBox33->Text).ToPointer();
PostnC  =( wchar_t *)Marshal::StringToHGlobalUni(this->textBox32->Text).ToPointer();
DeptC   =( wchar_t *)Marshal::StringToHGlobalUni(this->comboBox4->Text).ToPointer();
AnnLvC  =( wchar_t *)Marshal::StringToHGlobalUni(this->textBox9->Text).ToPointer();
EmrgLvC=( wchar_t *)Marshal::StringToHGlobalUni(this->textBox30->Text).ToPointer();
IrrC=( wchar_t *)Marshal::StringToHGlobalUni(this->comboBox1->SelectedItem->ToString()).ToPointer();
HmTwnC  =( wchar_t *)Marshal::StringToHGlobalUni(this->textBox25->Text).ToPointer();

我必须释放所有这些,例如:

Marshal::FreeHGlobal((IntPtr)EmpNameC);      
Marshal::FreeHGlobal((IntPtr)DtbrthC);
Marshal::FreeHGlobal((IntPtr)PlcBrthC);
Marshal::FreeHGlobal((IntPtr)CIDC);
Marshal::FreeHGlobal((IntPtr)ContNoC);
Marshal::FreeHGlobal((IntPtr)JndtC);
Marshal::FreeHGlobal((IntPtr)PostnC);
Marshal::FreeHGlobal((IntPtr)DeptC);
Marshal::FreeHGlobal((IntPtr)AnnLvC);
Marshal::FreeHGlobal((IntPtr)EmrgLvC);
Marshal::FreeHGlobal((IntPtr)IrrC);
Marshal::FreeHGlobal((IntPtr)HmTwnC);

有没有更短的方法可以用来释放所有本机对象,而不是每个对象一次?

4

1 回答 1

2

您可以使用包含队列的专用结构来管理它。

每次你分配一个本地对象时,你将它推入队列,最后你在一个循环中释放它们。

于 2012-12-10T09:36:05.830 回答