if I have multiple native type variables such:
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();
I must free all of them like:
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);
Is there any shorter way I can use to free all native objects instead of doing that once per one object?
You could manage it with a dedicated structure that holds a queue.
Each time you allocate a native object you push it into the queue, and at the end you free them all in a loop.