C# oneoof help

1,103 views
Skip to first unread message

David Vescovi

unread,
Jul 15, 2017, 9:53:54 AM7/15/17
to Protocol Buffers
First I tried this simple protobuf with compiler 3.3:

syntax = "proto3";


message ProxyMessage {

int32 Signal = 1;

oneof payload

 {

  repeated int32 a= 6;

  repeated float b = 7;

  }

}



while this seem quite simple it resulted in the following error:
protoc --csharp_out=. proxy.proto
proxy.proto:7:7: Fields in oneofs must not have labels (required / optional / repeated).
proxy.proto:8:7: Fields in oneofs must not have labels (required / optional / repeated).


Is there a workaround? Is this a known bug?


I know you can, in effect,  do this same thing in proto3 by not using the oneof and rely on "optional by default" feature.
The reason I need the oneof is the fact on the other end I am using C++ and I need the oneof union feature to keep the buffer allocation down.
That being said I really need something like:


syntax = "proto3";

 

message A

{

   repeated int32 Int32Parameters = 1;

}


message B

{

   repeated float FloatParameters = 1;

}

 

message ProxyMessage {

int32 Signal = 1;

oneof payload

  {

  A a= 6;

  B b = 7;

  }

}


This actually compiles but when I try to construct a message by doing something like this:

public MainPage()

{

  this.InitializeComponent();

  RepeatedField<int> myInts = new RepeatedField<int>();


  myInts.Add(2);

  myInts.Add(3);


  ProxyMessage proxy = new ProxyMessage();

  proxy.Signal = 5;

  proxy.A.Int32Parameters.AddRange(myInts);

}



I get a NullReferenceException when it hits the AddRange line.


I also tried adding the line:

proxy.PayloadCase = ProxyMessage.PayloadOneofCase.A;


but this will not compile with "..can not assigned to --it is read only"



any ideas?


Dave





Marc Gravell

unread,
Jul 15, 2017, 11:12:30 AM7/15/17
to David Vescovi, Protocol Buffers
the language guide is very clear and explicit that this is intentional; it is nothing to do with the C# part, and will behave the same for any language:

You can add fields of any type, but cannot use the requiredoptional, or repeated keywords.


And:

A oneof cannot be repeated.


So: no, you can't do what you want here. Maybe use encapsulation. So: have a message that *contains* a repeated field, and use that message type in the one-of.


--
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+unsubscribe@googlegroups.com.
To post to this group, send email to prot...@googlegroups.com.
Visit this group at https://groups.google.com/group/protobuf.
For more options, visit https://groups.google.com/d/optout.

David Vescovi

unread,
Jul 15, 2017, 11:35:15 AM7/15/17
to Protocol Buffers
simple resolution to the second issue ...forgot the proxy.A = new A();


oops. 
Reply all
Reply to author
Forward
0 new messages