RoQuOTriX
RoQuOTriX

Reputation: 3001

Correct way to convert array<unsigned char>^ to std::string

I wanted to know what is the correct way to convert a managed array<unsigned char>^ to an unmanaged std::string. What I do right now is this:

array<unsigned char>^ const content = GetArray();
auto enc = System::Text::Encoding::ASCII;
auto const source = enc->GetString(content);
std::string s = msclr::interop::marshal_as<std::string>(source);

Is there a way to marshal the content in one step to a std::string without converting to a String^?

I tried:

array<unsigned char>^ const content = GetArray();
std::string s = msclr::interop::marshal_as<std::string>(content);

but this gave me following errors:

Error   C4996   'msclr::interop::error_reporting_helper<_To_Type,cli::array<unsigned char,1> ^,false>::marshal_as': 
This conversion is not supported by the library or the header file needed for this conversion is not included.  
Please refer to the documentation on 'How to: Extend the Marshaling Library' for adding your own marshaling method.

Error   C2065   '_This_conversion_is_not_supported': undeclared identifier  

Upvotes: 0

Views: 1035

Answers (1)

David Yaw
David Yaw

Reputation: 27864

If the array is of plain bytes, then it's already ASCII encoded (or whatever narrow characters you're using). Converting to a managed UTF-16 String^ is an unnecessary detour.

Just construct a narrow-characters string from the byte array. Pass a pointer to the first byte and the length.

array<unsigned char>^ const content = GetArray();
pin_ptr<unsigned char> contentPtr = &content[0];
std::string s(contentPtr, content->Length);

I'm not at a compiler right now, there may be trivial syntax errors.

Upvotes: 2

Related Questions