Skip to content

Instantly share code, notes, and snippets.

@mcpherson mcpherson/butt.cc
Created Mar 21, 2016

Embed
What would you like to do?
Two methods for setting nested messages in protobuf
#include "butt.pb.h"
#include <string>
#include <iostream>
int main(int argc, char ** argv)
{
// Args: option 1: long string of pointers
butt::Args args;
args.set_k(99); // k
args.mutable_the_state()->set_single_double(100.0);
for (int i=0; i<9; i++) {
args.mutable_the_state()->mutable_array_double()->add_a((double)i); // array_double
}
std::string packed_string;
args.SerializeToString(&packed_string);
std::cout << args.DebugString();
// Args: option 2: set individually and add
// Setup State
butt::State *state(new butt::State);
state->set_single_double(100.0); // single_double
for (int i=0; i<9; i++) {
state->mutable_array_double()->add_a((double)i); // array_double
}
// Setup Aargs, adding the previously build State
butt::Args aargs;
aargs.set_k(99); // k
aargs.set_allocated_the_state(state);
std::string ppacked_string;
aargs.SerializeToString(&ppacked_string);
std::cout << aargs.DebugString();
}
package butt;
message DArray {
repeated double a = 1 [packed=true];
}
message State {
required double single_double = 1;
required DArray array_double = 2;
}
message Args {
required int32 k = 1;
required State the_state = 2;
}
@mcpherson

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.