5

我有Stream我需要通过 protobuf 消息作为bytes. 如何将 protobuf 转换StreamByteStringprotobuf 所期望的?它是否像文档序列化中显示的那样简单?

由于项目的性质,我无法很好地测试它,所以我有点盲目工作。这是我正在使用的内容:

协议缓冲区:

message ProtoResponse {
   bytes ResponseValue = 1;
}

C#

public ProtoResponse SendResponse(Stream stream)
{
   var response = ProtoResponse
      {
         // this obviously does not work but 
         // but it conveys the idea of what I am going for
         ResponseValue = stream
      }
   return response;
}

我试图将 转换Stream为 astring或 abyte[]但 VS 中的 C# 编译器一直显示此错误消息:

Cannot implicitly convert type '' to 'Google.Protobuf.ByteString'.

我知道我错过了一些东西,我的知识Streamsprotocol buffers缺乏。

4

2 回答 2

9

实际上,我可能已经回答了我自己的问题。ByteString有一个接受byte[].

public ProtoResponse SendResponse(Stream stream)
{
   byte[] b;
   using (var memoryStream = new MemoryStream())
   {
      stream.CopyTo(memoryStream);
      b = memoryStream.ToArray();
   }
   var response = ProtoResponse
      {
         ResponseValue = ByteString.CopyFrom(b)
      }
   return response;
}

如果有人发现这有什么问题,请随时告诉我!谢谢!

于 2019-03-21T15:01:10.750 回答
1

我使用 C#,Protobufsyntax = 3;GRPC. 就我而言,它看起来像这样:

我找到了将 Image 更改为 ByteArray 的方法,此示例用于了解我的回复的下一部分。

private static byte[] ImageToByteArray(Bitmap image)
{
  using (var ms = new MemoryStream())
   {
     image.Save(ms, image.RawFormat);
     return ms.ToArray();
   }
}

但是,接下来我必须将Bytearray更改为Protobuf3的ByteString

byte[] img = ImageToByteArray(); //its method you can see above
ByteString bytestring;
 using (var str = new MemoryStream(img))
 {
    bytestring = ByteString.FromStream(str);
 }

你可以简单地使用ByteString.FromStream(MemoryStream)没有CopyFrom方法。

如果我们查看此消息的接收者,他需要将ByteString更改为ByteArray以例如保存照片:

byte[] img = request.Image.ToByteArray(); //this is received message

就这样。你在两边都有完全相同的字节。

于 2019-07-22T13:35:45.930 回答