pospec4444
pospec4444

Reputation: 364

Converting CLI array to std::string without for-cycle

I want to convert array<unsigned char>^ to std::string. Is it possible to do the conversion without iterating over the array and assigning each character in string?

This is my "best" solution (and I don't like the assigning in for-cycle):

std::string CliArray2String(array<unsigned char>^ aSource)
{
    std::string strResult("");
    if (aSource != nullptr)
    {
        int iLength = aSource->GetLength(0);
        strResult.reserve(iLength + 1);
        for (int i = 0; i < iLength; i++)
            strResult[i] = aSource[i];
    }
    return strResult;
}

Thanks for your opinions.

Upvotes: 0

Views: 655

Answers (1)

Yochai Timmer
Yochai Timmer

Reputation: 49251

You can use the string range constructor, and pin the managed array.

pin_ptr<unsigned char> p = &aSource[0];
unsigned char *unmanagedP = p;
std::string str(unmanagedP , unmanagedP + aSource->GetLength(0));

or the sequence constructor:

std::string str(unmanagedP , aSource->GetLength(0));

Upvotes: 1

Related Questions