[英]How do I deserialize a binary AMQP message received with protobuf-net?
I am just learning C# and am using it with Godot.我正在学习 C# 并将其与 Godot 一起使用。 We are trying to send a binary Protobuf-encoded message from a client over AMQP and receive it with the C# script running in Godot.
我们正在尝试通过 AMQP 从客户端发送二进制 Protobuf 编码的消息,并使用在 Godot 中运行的 C# 脚本接收它。
I am at the point where the message is received and I am trying to deserialize it.我正处于收到消息的位置,我正在尝试反序列化它。 The message body is a 44-byte array, but the protobuf.net deserialize doesn't take a byte array.
消息正文是一个 44 字节的数组,但 protobuf.net 反序列化不采用字节数组。 The message body is of type
object
but it definitely contains a byte array.消息正文是
object
类型,但它肯定包含一个字节数组。
byte[] binaryBody = (byte[])message.Body;
CommandBuffer commandBuffer;
commandBuffer = Serializer.Deserialize<CommandBuffer>(binaryBody);
This results in an error:这会导致错误:
The call is ambiguous between the following methods or properties: 'Serializer.Deserialize<T>(ReadOnlyMemory<byte>, T, object)' and 'Serializer.Deserialize<T>(ReadOnlySpan<byte>, T, object)' [srt-godot-test]csharp(CS0121)
Trying to convert binaryBody
to a MemoryStream
results in all kind of a mess and a protobuf that cannot be properly decoded:尝试将
binaryBody
转换为MemoryStream
会导致各种混乱和无法正确解码的 protobuf:
MemoryStream st = new MemoryStream();
st.Write(binaryBody, 0, binaryBody.Length);
It seems like I should just be able to deserialize binaryBody
somehow, but I cannot figure out what to do here.似乎我应该能够以某种方式反序列
binaryBody
,但我不知道该怎么做。
I found this post: Protobuf.net Serialize/Deserialize to/from byte arrays我发现这篇文章: Protobuf.net Serialize/Deserialize to/from byte arrays
Which lead me to the MemoryStream
page: https://learn.microsoft.com/en-us/do.net/api/system.io.memorystream.-ctor?redirectedfrom=MSDN&view.net-6.0#System_IO_MemoryStream__ctor_System_Byte__ _这将我带到
MemoryStream
页面: https://learn.microsoft.com/en-us/do.net/api/system.io.memorystream.-ctor?redirectedfrom=MSDN&view.net-6.0#System_IO_MemoryStream__ctor_System_Byte__ _
And I noticed this option: https://learn.microsoft.com/en-us/do.net/api/system.io.memorystream.-ctor?view.net-6.0#system-io-memorystream-ctor(system-byte()-system-boolean)我注意到这个选项: https://learn.microsoft.com/en-us/do.net/api/system.io.memorystream.-ctor?view.net-6.0#system-io-memorystream-ctor(system -byte()-系统布尔值)
Which resulted in this code:这导致了这段代码:
void GameEventReceived(IReceiverLink receiver, Message message)
{
GD.Print("Event received!");
// accept the message so that it gets removed from the queue
receiver.Accept(message);
byte[] binaryBody = (byte[])message.Body;
MemoryStream st = new MemoryStream(binaryBody, false);
// prep a command buffer for processing the message
CommandBuffer commandBuffer;
commandBuffer = Serializer.Deserialize<CommandBuffer>(st);
}
The key was creating the MemoryStream
directly from the bytestring.关键是直接从字节串创建
MemoryStream
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.