I am trying to convert a managed byte array to std::string in my C++/CLI wrapper; however, I am seeing some corrupt memory in the heap later on. Just wanted to check if I am doing the conversion right. Below is my method is CLI:
string ByteArrayToStr(array<Byte>^ byteArray)
{
int size = byteArray.Length;
IntPtr pnt = Marshal::AllocHGlobal(size + 1);
char* chararray = (char*)pnt.ToPointer();
try
{
Marshal::Copy(byteArray, 0, pnt, size);
*(chararray + size) = 0;
return string(chararray);
}
finally
{
Marshal::FreeHGlobal(pnt);
}
}
Does anything seem wrong in above code?
tryblock to usechararray[site], but that would be just more readable, it wouldn't change what the code does.