如何修复 c# protobuf-net 中的无效线型问题
Posted
技术标签:
【中文标题】如何修复 c# protobuf-net 中的无效线型问题【英文标题】:How to fix Invalid wire-type issue in c# protobuf-net 【发布时间】:2022-01-14 20:54:44 【问题描述】:我正在将 protobuf-net 反序列化调用从通用调用转换为指定类型。
using var memStream = new MemoryStream(bytes);
var result = Serializer.Deserialize<T>(memStream);
到
using var memStream = new MemoryStream(bytes);
var result = Serializer.Deserialize(memStream, type);
我得到一个例外
ProtoBuf.ProtoException: Invalid wire-type (Fixed64); this usually means you have over-written a file without truncating or setting the length; see https://***.com/q/2152978/23354
at ProtoBuf.ProtoReader.State.ThrowProtoException(String message) in /_/src/protobuf-net.Core/ProtoReader.State.ReadMethods.cs:line 764
at ProtoBuf.ProtoReader.State.ThrowWireTypeException() in /_/src/protobuf-net.Core/ProtoReader.State.ReadMethods.cs:line 758
at ProtoBuf.Internal.PrimaryTypeProvider.ProtoBuf.Serializers.ISerializer<System.Type>.Read(State& state, Type value) in /_/src/protobuf-net.Core/Internal/PrimaryTypeProvider.Primitives.cs:line 292
at ProtoBuf.ProtoReader.State.<ReadAsRoot>g__ReadFieldOne|102_0[T](State& state, SerializerFeatures features, T value, ISerializer`1 serializer) in /_/src/protobuf-net.Core/ProtoReader.State.ReadMethods.cs:line 1075
at ProtoBuf.ProtoReader.State.ReadAsRoot[T](T value, ISerializer`1 serializer) in /_/src/protobuf-net.Core/ProtoReader.State.ReadMethods.cs:line 1059
at ProtoBuf.ProtoReader.State.DeserializeRoot[T](T value, ISerializer`1 serializer) in /_/src/protobuf-net.Core/ProtoReader.State.ReadMethods.cs:line 1036
at ProtoBuf.Serializer.Deserialize[T](Stream source, T value, Object userState, Int64 length) in /_/src/protobuf-net/Serializer.Deserialize.cs:line 43
at Computer.Bus.Integration.ProtoSerializer.Deserialize(Byte[] bytes, Type type) in C:\Users\squir\source\repos\Computer.Bus\source\Computer.Bus.Integration\ProtoSerializer.cs:line 21
at Computer.Bus.RabbitMq.Client.BusClient.<>c__DisplayClass6_0.<<Subscribe>g__innerCallback|0>d.MoveNext() in C:\Users\squir\source\repos\Computer.Bus\source\Computer.Bus.RabbitMq\Client\BusClient.cs:line 52
我所有寻找解决方案的尝试通常都与序列化错误或字节管理有关。这是一个简单的应用程序。我正在尝试(反)序列化在同一源中声明的简单类型。
[ProtoContract]
public record ProtoModel
[ProtoMember(1)]
public double fNumber get; init; = DateTime.Now.ToBinary();
[ProtoMember(2)]
public string someString get; init; = "something";
[ProtoMember(3)]
public DateTime Timestamp get; init; = DateTime.Now;
【问题讨论】:
【参考方案1】:在我做了一些挖掘之后,我发现我把参数的顺序放错了。反序列化应该是这样的
using var memStream = new MemoryStream(bytes);
var result = Serializer.Deserialize(type, memStream);
【讨论】:
以上是关于如何修复 c# protobuf-net 中的无效线型问题的主要内容,如果未能解决你的问题,请参考以下文章
Protobuf-net 使用嵌套数据反序列化时出现无效的线型异常(C++ 到 C#)
ProtoBuf-Net 错误消息“源数据中的无效字段:0”
C# Protobuf-net:如何从网络流中连续反序列化?
protobuf-net运行在Unity上,修复IL2CPP反射不兼容问题