Question

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?

Was it helpful?

Solution

You are doing an unnecessary explicit copy and playing with a manual memory allocation.

You could just pass the raw pinned pointer to std::string constructor:

string ByteArrayToStr(array<Byte>^ byteArray)
{
    pin_ptr<unsigned char> temp = &byteArray[0];
    return string(reinterpret_cast<char*>(temp), byteArray->Length);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top