FreeHGlobal()是否需要释放函数中传递的非托管字符串?

时间:2015-06-11 04:11:28

标签: .net string c++-cli unmanaged

如果我有以下代码:

void foo (String^ v)
{
   WCHAR someString[256];
   _tcscpy_s(someString, (LPCTSTR)Marshal::StringtoHGLobalUni(v).ToPointer());
}

在这种情况下我还需要使用FreeHGlobal()吗?如果是这样,为什么?复制功能不会处理这种全局分配吗?

1 个答案:

答案 0 :(得分:2)

是的,FreeHGlobal是必要的。 _tcscpy_s不知道缓冲区的来源;它不知道释放缓冲区。

如果你想要一个自动释放,你会想要使用一些足够智能的对象,当它离开范围时可以免费使用。 marshal_context在这里是个不错的选择。

void foo (String^ v)
{
    marshal_context context;
    WCHAR someString[256];
    _tcscpy_s(someString, context.marshal_as<const TCHAR*>( v ));
} // <-- The marshal_context, and the unmanaged memory it owns, 
  //     are cleaned up at the end of the function.

(免责声明:我不是编译器,可能存在语法错误。)