使用StringToHGlobalAnsi将System :: String转换为函数中的char *

时间:2011-07-18 13:53:17

标签: string char c++-cli interop mixed-mode

我需要在System::String^char*的CLI包装器中进行多次转换,并且我编写了一个函数,但在返回char*之前我无法释放堆空间! (随着时间的推移获得堆错误)

转换

char* ManagedReaderInterface::SystemStringToChar(System::String ^source)
{           
    char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(source);

    return str2;
}

我使用的功能如下:

GetSomething(SystemStringToChar(str), value);

有什么想法吗?!

2 个答案:

答案 0 :(得分:4)

最终,有人需要负责释放存储返回值的内存。它不能是你的转换函数,因为它会在你想要释放内存之前返回。

如果您使用std::string而不是原始char*,这一切都会变得更容易。试试这个:

#include <msclr/marshal_cppstd.h>
...     
GetSomething(msclr::interop::marshal_as<std::string>(str).c_str(), value);

答案 1 :(得分:2)

在每一种方法中:

IntPtr memHandle = Marshal::StringToHGlobalAnsi(string);

try
{
    char *charStr = static_cast<char*>(memHandle .ToPointer());

    // do something with charStr

    Marshal::FreeHGlobal(memHandle); // free space -> Attention: don't delete it to soon
}
catch
{
    ...
}   

现在应该干净!