Petr
Petr

Reputation: 63399

Is it possible to construct an empty Message from a Descriptor?

That is, given a Descriptor, is it possible to construct the corresponding empty Message equivalent to calling default_instance() on the class? I don't need the actual subtype, I need only the abstract Message.

In particular I'm interested in enumerating instances of all Messages in a protobuf file, but using the API I was only able to enumerate all their Descriptors.

Upvotes: 0

Views: 1201

Answers (1)

Kenton Varda
Kenton Varda

Reputation: 45276

The interface you're looking for is MessageFactory. Given a Descriptor, it can give you a default instance of that type. (You can call message->New() on the default instance to get a new mutable instance.)

There are two main kinds of MessageFactory. If the types you are interested in are compiled into your program binary, then you want to use MessageFactory::generated_factory(), which returns a MessageFactory that instantiates compiled-in types.

If the types are not compiled in, then you'll want to create a DynamicMessageFactory, which is able to construct a Message behaving like any arbitrary type -- but note that due to the dynamic nature, using this instance will be slower than a compiled-in type (much like interpreted languages are slower than compiled ones).

Upvotes: 1

Related Questions