2012-07-06 134 views
1

我知道这是一个经常被问到的问题,我没有明确的答案将std :: string或String ^转换为字节数组来写入到一个用于tcp通信的流。将std :: string或string ^转换为C++/cli中的字节数组

这是我曾尝试

bool CTcpCommunication::WriteBytes(const std::string& rdatastr) 
{ 
    bool retVal = false; 

    try 
    { 
    if (static_cast<NetworkStream^>(stream) != nullptr) 
    { 
     array<Byte>^data = System::Text::Encoding::ASCII->GetBytes(rdatastr); 
     stream->Write(data, 0, data->Length); 
    } 
    } 
    catch(Exception^) 
    { 
    // Ignore, just return false 
    } 
    return retVal; 
} 

我知道这里的GetBytes会不会工作,我还检查编组选项STD转换:字符串.NET字符串,但还没有发现有人any.Can帮助我在解决这个问题..

+0

封送处理到.NET字符串,这是很好描述*无处不在*,与此无关,你正在试图制作一个'数组' – 2012-07-06 04:29:14

回答

5

编码已经是正确的,不需要转换。只需复制:

array<Byte>^ data = gcnew array<Byte>(rdatastr.size()); 
System::Runtime::InteropServices::Marshal::Copy(IntPtr(&rdatastr[0]), data, 0, rdatastr.size()); 
+0

@ShivShambo:已添加全名。 – 2012-07-06 04:36:38

+0

..谢谢..错误现在说C2440:'':不能从'const char *'转换为'System :: IntPtr' – ShivShambo 2012-07-06 06:18:25

+0

我改变了一下它的工作..我更新了 – ShivShambo 2012-07-06 07:40:56

0

这个工作对me..Thanks奔

IntPtr ptr((void*)rdatastr.data()); 
array<Byte>^ data = gcnew array<Byte>(rdatastr.size()); 
System::Runtime::InteropServices::Marshal::Copy(ptr, data, 0, rdatastr.size()) 
+0

另请参阅http://stackoverflow.com/a/10380166/45603 – 2012-07-06 12:15:45