I use protobuf's enums to share values between a C++ app and a Java app. This way, the same (int
) values are shared between languages and the values are available at compile time. Can I do something similar with a string by somehow defining it in the common .proto
file?
Asked
Active
Viewed 3.9k times
28

ytoledano
- 3,003
- 2
- 24
- 39
-
My spontaneous answer is no. Why do you want to share a string. Is you have two modules communicating it will be a waste of bandwidth to transmit a string instead of a enum constant. – Emil Mar 01 '16 at 09:17
-
2Protobuf allows enums, those enums can, but don't have to be transmitted over the wire. If I use an enum, which is basically a constant, in both my C++ and Java apps, I'm not transmitting anything over the wire, yet they're both using the same value, defined in the `.proto`. – ytoledano Mar 01 '16 at 09:19
-
I had a similar issue a while ago trying to associate strings with enums, does the answer here help you? http://stackoverflow.com/questions/11474416/define-dictionary-in-protocol-buffer – user812786 Mar 02 '16 at 18:17
1 Answers
38
Not really.
There are a few hacks you can use. Neither is a great fit, and (I think) both are going away in proto3:
- Define a message with a string field and give it a default value which is your constant value. However, Protobuf 3 is removing default values, apparently.
- Use "custom options", which should probably have been called "annotations" as they are much like annotations in Java or other languages. You can declare an annotation of type string, then annotate some dummy declaration with your annotation and use the constant value. However, custom options are based on extensions which are also removed in proto3, so I assume custom options have been removed too. (This is the answer offered here: https://stackoverflow.com/a/11486640/2686899.)
FWIW, Cap'n Proto, an alternative to protocol buffers, does support constants. (Disclosure: I am the author of Cap'n Proto as well as most of Google's Protobuf v2.)

Community
- 1
- 1

Kenton Varda
- 41,353
- 8
- 121
- 105
-
I ended up using option 1. I defined a message with fields with default values in it and then used the default instance to access them. It was quite clean, but like noted above, isn't supported in protobuf 3. One reason it was useful is that you get all of protobuf "reflection" capabilities: iterate over fields, get field by number/name... – ytoledano Jun 17 '17 at 09:46
-
4The docs for proto3 say "Note that creating custom options uses extensions, which are permitted only for custom options in proto3". The proto3 docs link to the proto2 docs for custom options in @kenton-varda 's answer. – NYCdotNet Dec 05 '18 at 14:56
-
1
-
@user1870400 If you are asking about extensions, then yes. But Custom Options, that are made using extensions, are left. Therefore there is exception for extensions. – A. Lisowski Sep 24 '20 at 10:10