How to serialize empty message in protobuf-3 in C++?

1,614 views
Skip to first unread message

Ivan Baidakou

unread,
Feb 5, 2021, 3:57:43 PM2/5/21
to Protocol Buffers

Hi,

There is a the following message type:

message Ping {}

When I invoke for my  object  "proto::Ping &ping" the ping.ByteSizeLong() it returns zero. ping.SerializeAsString() also returns empty string.

What can be done?

Thank you,
wbr, basiliscos

Nadav Samet

unread,
Feb 5, 2021, 4:05:39 PM2/5/21
to Ivan Baidakou, Protocol Buffers
Hi Ivan,

You are doing it correctly. An empty message has zero length when serialized. This is also true for messages with only optional fields - an empty array of bytes is a valid serialized instance of such a message.

-Nadav

--
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to protobuf+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/protobuf/c5cfa7ca-bd7f-47b5-a993-0427b0e04d06n%40googlegroups.com.


--
-Nadav

Ivan Baidakou

unread,
Feb 5, 2021, 4:26:28 PM2/5/21
to Protocol Buffers
Hi Nadav,

I have to send the message over the network. If it returns the empty string, there is nothing to send. Anyway, I can see, that the remote side somehow sends (empty) Pings to me. How I can do the same?

Nadav Samet

unread,
Feb 5, 2021, 5:12:44 PM2/5/21
to Ivan Baidakou, Protocol Buffers
Over the network, you could send the size of the message (which may be zero) and then the message itself. See the example on this page and steaming multiple messages



--
-Nadav

Ivan Baidakou

unread,
Feb 5, 2021, 5:36:51 PM2/5/21
to Protocol Buffers
Thanks a lot, it helped greatly!
Reply all
Reply to author
Forward
0 new messages