Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

protobuf-c: How to pack nested messages

I have a Protobuf Protocol file that looks something like this:

message Foo {
    message Bar {
        required string name = 1;
        required string value = 2;
    }

    message Baz {
        required Bar a = 1;
    }
}

Given this protocol file, I need to write an encoder using protobuf-c, the C extension for Protobuf. I wrote the following code:

Foo myfoo = FOO__INIT;
Foo__Bar mybar = FOO__BAR__INIT;
Foo__Baz mybaz = FOO__BAZ__INIT;
mybaz.a = &mybar;

However, I am stuck at this point on how to serialize mybaz. The generated struct for Foo, does not contain any entry that I can assign mybaz to. And no method for generated to directly pack Baz.

In Python, this was a lot more simpler, since a mybaz.SerializeToString() function had been generated. How should I go about this in C?

like image 469
darnir Avatar asked Mar 16 '23 01:03

darnir


1 Answers

Declaring nested types in Protocol Buffers is like declaring nested classes in C++ or static inner classes in Java. This simply declares a new type; it does not add a field to the outer type. So, in your proto schema, Foo is a completely empty message -- it has no fields. This is true regardless of which programming language you're working in.

Probably what you meant to do is something like this:

message Foo {
  message Bar {
    required string name = 1;
    required string value = 2;
  }

  message Baz {
    required Bar a = 1;
  }

  optional Baz baz = 1;
}

Now Foo has a field called baz into which you can assign a Baz object.

like image 162
Kenton Varda Avatar answered Mar 29 '23 06:03

Kenton Varda