0

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.

5
  • std::string or std::wstring? Commented Aug 18, 2014 at 8:44
  • 1
    Unrelated to your question, but you declare strResult as a narrow-character string, but the return type is a wide-character string. Commented Aug 18, 2014 at 8:45
  • Sorry, I meant std::string. Commented Aug 18, 2014 at 8:47
  • 2
    Use pin_ptr msdn.microsoft.com/en-us/library/1dz8byfh.aspx Commented Aug 18, 2014 at 9:04
  • This is a non-trivial and lossy conversion, you cannot cram a Unicode codepoint into a byte. That for-loop is going to be somewhere, doesn't much matter where. You can pretend it doesn't exist with Marshal::StringToHGlobalAnsi() for example. Commented Aug 20, 2014 at 13:02

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

1 Comment

That still iterates, but at least it doesn't look like it is. The answer to the original question is, of course, "no."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.