本文介绍了协议缓冲区 c# (protobuf-net) Message::ByteSize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找与 C++ API Message::ByteSize 等效的 protobuf-net,以找出以字节为单位的序列化消息长度.

解决方案

我没有玩过 C++ API,所以你必须给我更多的上下文/信息.这个方法有什么作用?也许是示例用法?

如果您从流中消费数据,有WithLengthPrefix"版本可以自动限制为谨慎的消息,或者我相信只读取下一个长度的方法来自流的公共 API.

如果您想获得序列化的长度,那么目前我怀疑最简单的选择可能是序列化为虚拟流并跟踪长度.奇怪的是,protobuf-net 的早期版本确实有无需做工作就能得到长度"的方法,但在对 protobuf-net 进行讨论后,我删除了这些方法.显然,序列化的数据仍然被跟踪.但是,由于 API 与对象的二进制数据长度不同,因此不能免费"使用.

如果您阐明用例是什么,我相信我们可以使其易于使用(如果还没有).

重新评论;这就是我所怀疑的.因为 protobuf-net 将二进制转换推迟到最后一刻(因为它处理的是常规的 .NET 类型,而不是一些自生成的代码),所以没有自动获取这个值而不做这项工作.我可以添加一种机制,让您通过写入 Stream.Null 来获取此值?但是如果您无论如何需要数据,您可能会受益于在复制数据之前写入MemoryStream并检查.Length.>

I am looking for the protobuf-net equivalent to the C++ API Message::ByteSize to find out the serialized message length in bytes.

解决方案

I haven't played with the C++ API, so you'll have to give me a bit more context / information. What does this method do? Perhaps a sample usage?

If you are consuming data from a stream, there are "WithLengthPrefix" versions to automate limiting to discreet messages, or I believe the method to just read the next length from the stream is on the public API.

If you want to get a length in place of serializing, then currently I suspect the easiest option might be to serialize to a dummy stream and track the length. Oddly enough, an early version of protobuf-net did have "get the length without doing the work" methods, but after discussion on the protobuf-net I removed these. The data serialized is still tracked, obviously. However, because the API is different than the binary data length for objects is not available "for free".

If you clarify what the use-case is, I'm sure we can make it easily available (if it isn't already).


Re the comment; that is what I suspected. Because protobuf-net defers the binary translation to the last moment (because it is dealing with regular .NET types, not some self-generated code) there is no automatic way of getting this value without doing the work. I could add a mechanism to let you get this value by writing to Stream.Null? but if you need the data anyway you might benefit from just writing to MemoryStream and checking the .Length in advance of copying the data.

这篇关于协议缓冲区 c# (protobuf-net) Message::ByteSize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:13