【问题标题】:Converting std::string or string^ to byte array in c++/cli在 c++/cli 中将 std::string 或 string^ 转换为字节数组
【发布时间】:2016-08-23 15:06:02
【问题描述】:

我知道这是一个常见问题,但对于将 std::string 或 String^ 转换为字节数组以写入流以进行 tcp 通信,我还没有明确的答案。

这是我尝试过的

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:string 转换为 .NET String 的编组选项,但还没有发现任何问题。有人可以帮我解决这个问题吗..

【问题讨论】:

  • Marshaling to .NET String,很好地描述了everywhere,与此无关,您正在尝试制作array&lt;Byte&gt;

标签: .net string sockets c++-cli tcpclient


【解决方案1】:

编码已经正确,无需转换。只需复制:

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

【讨论】:

  • @ShivShambo:添加了完整的类型名称。
  • ..thanks.. 错误现在显示 C2440: '' : cannot convert from 'const char *' to 'System::IntPtr'
  • @ShivShambo:哦,是的,愚蠢的 BCL 和缺乏 const 正确性。此修改应该可以修复它。
【解决方案2】:

这个方法怎么样:

String ^sTemp;
array<Byte> ^TxData;

sTemp = "Hello";
TxData = System::Text::Encoding::UTF8->GetBytes(sTemp);

链接:http://www.electronic-designer.co.uk/visual-cpp-cli-dot-net/strings/convert-string-to-byte-array

【讨论】:

    【解决方案3】:

    这对我有用..感谢 Ben

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 2016-01-28
      相关资源
      最近更新 更多