Re: why memory leak here?
"Vivienne" <zhoudan.bupt@gmail.com> ha scritto nel messaggio
news:1190097684.943523.50720@y42g2000hsy.googlegroups.com...
I am using a c# library in my c++ project, so the function that
convert System::String to basic_string is often called. But when
debugging, I get the memory leak report.
here is the function:
void convert(System::String ^ s, std::string& os ){
using namespace Runtime::InteropServices;
pin_ptr<const wchar_t> wch = PtrToStringChars(s);
Hi,
I'm not a C++/CLI expert, however, why don't you use
Marshal::StringToHGlobalAnsi for the conversion?
e.g.
void Convert(
System::String ^ sIn, // input - managed string
std::string & sOut // output - unmanaged string
)
{
// Marshal the managed string to unmanaged memory
char * stringPtr = (char *) Marshal::StringToHGlobalAnsi(
sIn ).ToPointer();
// Deep-copy to std::string
sOut = std::string( stringPtr );
// Free the temporary unmanaged string memory
Marshal::FreeHGlobal( IntPtr(stringPtr) );
}
Note that I would very much prefer a conversion to *Unicode* strings, i.e.
use Marshal::StringToHGlobalUni, and use *std::wstring* instead of
std::string.
(I would use std::string just to store UTF-8 Unicode strings. I would really
consider ANSI strings as some form of computer archaeology :-)
Giovanni