将array<unsigned char>^转换为std::string的正确方法。

问题描述 投票:0回答:1

我想知道正确的转换托管的方法是什么?array<unsigned char>^ 到非管理型 std::string. 我现在要做的是:

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);

有什么办法可以调集... content 步步为营 std::string 而不转成 String^?

我试过了,但这给了我以下错误:

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

但这给了我以下错误。

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  
c++-cli
1个回答
2
投票

如果数组是纯字节,那么它已经被ASCII编码了(或者你正在使用的任何窄字符)。转换为托管的UTF-16 String^ 是一个不必要的弯路。

只需从字节数组中构造一个窄字符字符串。传递一个指向第一个字节的指针和长度。

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

我现在不在编译器旁,可能有琐碎的语法错误。

© www.soinside.com 2019 - 2024. All rights reserved.