If I have the following piece of code :
void foo (String^ v)
{
WCHAR someString[256];
_tcscpy_s(someString, (LPCTSTR)Marshal::StringtoHGLobalUni(v).ToPointer());
}
Would I still need to use FreeHGlobal()
in this case? And if so, why? Would the copy function not take care of this global allocation?
Yes,
FreeHGlobal
is necessary._tcscpy_s
has no knowledge of where the buffer came from; it doesn't know to free the buffer.If you wanted an automatic free, you'll want to use some object that is smart enough to do the free when it leaves scope.
marshal_context
is a good choice here.(Disclaimer: I'm not at a compiler, there may be syntax errors.)