Chinaunix首页 | 论坛 | 博客
  • 博客访问: 634872
  • 博文数量: 116
  • 博客积分: 6078
  • 博客等级: 准将
  • 技术积分: 1214
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-23 10:09
文章分类

全部博文(116)

文章存档

2016年(1)

2015年(4)

2011年(2)

2010年(21)

2009年(88)

分类: C/C++

2015-05-28 12:56:48

message.h

#include
namespace google::protobuf

Defines Message, the abstract interface implemented by non-lite protocol message objects.

Although it's possible to implement this interface manually, most users will use the protocol compiler to generate implementations.

Example usage:

Say you have a message defined as:

message Foo {
  optional string text = 1;
  repeated int32 numbers = 2;
}
Then, if you used the protocol compiler to generate a class from the above
definition, you could use it like so:
string data;  // Will store a serialized version of the message.

{
  // Create a message and serialize it.
  Foo foo;
  foo.set_text("Hello World!");
  foo.add_numbers(1);
  foo.add_numbers(5);
  foo.add_numbers(42);

  foo.SerializeToString(&data);
}

{
  // Parse the serialized message and check that it contains the
  // correct data.
  Foo foo;
  foo.ParseFromString(data);

  assert(foo.text() == "Hello World!");
  assert(foo.numbers_size() == 3);
  assert(foo.numbers(0) == 1);
  assert(foo.numbers(1) == 5);
  assert(foo.numbers(2) == 42);
}

{
  // Same as the last block, but do it dynamically via the Message
  // reflection interface.
  Message* foo = new Foo;
  const Descriptor* descriptor = foo->GetDescriptor();

  // Get the descriptors for the fields we're interested in and verify
  // their types.
  const FieldDescriptor* text_field = descriptor->FindFieldByName("text");
  assert(text_field != NULL);
  assert(text_field->type() == FieldDescriptor::TYPE_STRING);
  assert(text_field->label() == FieldDescriptor::LABEL_OPTIONAL);
  const FieldDescriptor* numbers_field = descriptor->
                                         FindFieldByName("numbers");
  assert(numbers_field != NULL);
  assert(numbers_field->type() == FieldDescriptor::TYPE_INT32);
  assert(numbers_field->label() == FieldDescriptor::LABEL_REPEATED);

  // Parse the message.
  foo->ParseFromString(data);

  // Use the reflection interface to examine the contents.
  const Reflection* reflection = foo->GetReflection();
  assert(reflection->GetString(foo, text_field) == "Hello World!");
  assert(reflection->FieldSize(foo, numbers_field) == 3);
  assert(reflection->GetRepeatedInt32(foo, numbers_field, 0) == 1);
  assert(reflection->GetRepeatedInt32(foo, numbers_field, 1) == 5);
  assert(reflection->GetRepeatedInt32(foo, numbers_field, 2) == 42);

  delete foo;
}

Classes in this file

RepeatedField is used to represent repeated fields of a primitive type (in other words, everything except strings and nested Messages).
RepeatedPtrField is like RepeatedField, but used for repeated strings or Messages.
A container to hold message metadata.
Abstract interface for protocol messages.
Forward-declare RepeatedFieldRef templates.
This interface contains methods that can be used to dynamically access and modify the fields of a protocol message.
Abstract interface for a factory for message objects.

template class RepeatedField

#include <google/protobuf/message.h>
namespace google::protobuf

template

RepeatedField is used to represent repeated fields of a primitive type (in other words, everything except strings and nested Messages).

Most users will not ever use a RepeatedField directly; they will use the get-by-index, set-by-index, and add accessors that are generated for all repeated fields.

Members

typedef
Element * iterator
STL-like iterator support.
typedef
const Element * const_iterator
typedef
Element value_type
typedef
value_type & reference
typedef
const value_type & const_reference
typedef
value_type * pointer
typedef
const value_type * const_pointer
typedef
int size_type
typedef
ptrdiff_t difference_type
typedef
std::reverse_iterator< const_iterator > const_reverse_iterator
Reverse iterator support.
typedef
std::reverse_iterator< iterator > reverse_iterator
RepeatedField()
explicit
RepeatedField(Arena * arena)
RepeatedField(const RepeatedField & other)
template
RepeatedField(Iter begin, const Iter & end)
~RepeatedField()
RepeatedField &
operator=(const RepeatedField & other)
bool
empty() const
int
size() const
const Element &
Get(int index) const
Element *
Mutable(int index)
void
Set(int index, const Element & value)
void
Add(const Element & value)
Element *
Add()
void
RemoveLast()
Remove the last element in the array.
void
ExtractSubrange(int start, int num, Element * elements)
Extract elements with indices in "[[]start .. start+num-1]". more...
void
Clear()
void
MergeFrom(const RepeatedField & other)
void
CopyFrom(const RepeatedField & other)
void
Reserve(int new_size)
Reserve space to expand the field to at least the given size. more...
void
Truncate(int new_size)
Resize the RepeatedField to a new, smaller size. This is O(1).
void
AddAlreadyReserved(const Element & value)
Element *
AddAlreadyReserved()
int
Capacity() const
void
Resize(int new_size, const Element & value)
Like STL resize. more...
Element *
mutable_data()
Gets the underlying array. more...
const Element *
data() const
void
Swap(RepeatedField * other)
Swap entire contents with "other". more...
void
UnsafeArenaSwap(RepeatedField * other)
Swap entire contents with "other". more...
void
SwapElements(int index1, int index2)
Swap two elements.
iterator
begin()
const_iterator
begin() const
const_iterator
cbegin() const
iterator
end()
const_iterator
end() const
const_iterator
cend() const
reverse_iterator
rbegin()
const_reverse_iterator
rbegin() const
reverse_iterator
rend()
const_reverse_iterator
rend() const
int
SpaceUsedExcludingSelf() const
Returns the number of bytes used by the repeated field, excluding sizeof(*this)
iterator
erase(const_iterator position)
Remove the element referenced by position.
iterator
erase(const_iterator first, const_iterator last)
Remove the elements in the range [[]first, last).
Arena *
GetArena() const
Get the Arena on which this RepeatedField stores its elements.

void RepeatedField::ExtractSubrange(
        int start,
        int num,
        Element * elements)

Extract elements with indices in "[[]start .. start+num-1]".

Copy them into "elements[[]0 .. num-1]" if "elements" is not NULL. Caution: implementation also moves elements with indices [[]start+num ..]. Calling this routine inside a loop can cause quadratic behavior.


void RepeatedField::Reserve(
        int new_size)

Reserve space to expand the field to at least the given size.

Avoid inlining of Reserve(): new, copy, and delete[[]] lead to a significant amount of code bloat.

If the array is grown, it will always be at least doubled in size.


void RepeatedField::Resize(
        int new_size,
        const Element & value)

Like STL resize.

Uses value to fill appended elements. Like Truncate() if new_size <= size(), otherwise this is O(new_size - size()).


Element * RepeatedField::mutable_data()

Gets the underlying array.

This pointer is possibly invalidated by any add or remove operation.


void RepeatedField::Swap(
        RepeatedField * other)

Swap entire contents with "other".

If they are separate arenas then, copies data between each other.


void RepeatedField::UnsafeArenaSwap(
        RepeatedField * other)

Swap entire contents with "other".

Should be called only if the caller can guarantee that both repeated fields are on the same arena or are on the heap. Swapping between different arenas is disallowed and caught by a GOOGLE_DCHECK (see API docs for details).

template class RepeatedPtrField

#include <google/protobuf/message.h>
namespace google::protobuf

template

RepeatedPtrField is like RepeatedField, but used for repeated strings or Messages.

Members

typedef
internal::RepeatedPtrIterator< Element > iterator
STL-like iterator support.
typedef
internal::RepeatedPtrIterator< const Element > const_iterator
typedef
Element value_type
typedef
value_type & reference
typedef
const value_type & const_reference
typedef
value_type * pointer
typedef
const value_type * const_pointer
typedef
int size_type
typedef
ptrdiff_t difference_type
typedef
std::reverse_iterator< const_iterator > const_reverse_iterator
Reverse iterator support.
typedef
std::reverse_iterator< iterator > reverse_iterator
typedef
internal::RepeatedPtrOverPtrsIterator< Element, void * > pointer_iterator
Custom STL-like iterator that iterates over and returns the underlying pointers to Element rather than Element itself.
typedef
internal::RepeatedPtrOverPtrsIterator< const Element, const void * > const_pointer_iterator
RepeatedPtrField()
explicit
RepeatedPtrField(Arena * arena)
RepeatedPtrField(const RepeatedPtrField & other)
template
RepeatedPtrField(Iter begin, const Iter & end)
~RepeatedPtrField()
RepeatedPtrField &
operator=(const RepeatedPtrField & other)
bool
empty() const
int
size() const
const Element &
Get(int index) const
Element *
Mutable(int index)
Element *
Add()
void
RemoveLast()
Remove the last element in the array. more...
void
DeleteSubrange(int start, int num)
Delete elements with indices in the range [[]start . more...
void
Clear()
void
MergeFrom(const RepeatedPtrField & other)
void
CopyFrom(const RepeatedPtrField & other)
void
Reserve(int new_size)
Reserve space to expand the field to at least the given size. more...
int
Capacity() const
Element **
mutable_data()
Gets the underlying array. more...
const Element *const *
data() const
void
Swap(RepeatedPtrField * other)
Swap entire contents with "other". more...
void
UnsafeArenaSwap(RepeatedPtrField * other)
Swap entire contents with "other". more...
void
SwapElements(int index1, int index2)
Swap two elements.
iterator
begin()
const_iterator
begin() const
const_iterator
cbegin() const
iterator
end()
const_iterator
end() const
const_iterator
cend() const
reverse_iterator
rbegin()
const_reverse_iterator
rbegin() const
reverse_iterator
rend()
const_reverse_iterator
rend() const
pointer_iterator
pointer_begin()
const_pointer_iterator
pointer_begin() const
pointer_iterator
pointer_end()
const_pointer_iterator
pointer_end() const
int
SpaceUsedExcludingSelf() const
Returns (an estimate of) the number of bytes used by the repeated field, excluding sizeof(*this).
protected Arena *
GetArenaNoVirtual() const
Internal arena accessor expected by helpers in Arena.

Advanced memory management

When hardcore memory management becomes necessary – as it sometimes does here at Google – the following methods may be useful.
void
AddAllocated(Element * value)
Add an already-allocated object, passing ownership to the RepeatedPtrFieldmore...
Element *
ReleaseLast()
Remove the last element and return it, passing ownership to the caller. more...
void
UnsafeArenaAddAllocated(Element * value)
Add an already-allocated object, skipping arena-ownership checks. more...
Element *
UnsafeArenaReleaseLast()
Remove the last element and return it. more...
void
ExtractSubrange(int start, int num, Element ** elements)
Extract elements with indices in the range "[[]start .. start+num-1]". more...
void
UnsafeArenaExtractSubrange(int start, int num, Element ** elements)
Identical to ExtractSubrange() described above, except that when this repeated field is on an arena, no object copies are performed. more...
int
ClearedCount() const
Get the number of cleared objects that are currently being kept around for reuse.
void
AddCleared(Element * value)
Add an element to the pool of cleared objects, passing ownership to the RepeatedPtrFieldmore...
Element *
ReleaseCleared()
Remove a single element from the cleared pool and return it, passing ownership to the caller. more...
iterator
erase(const_iterator position)
Remove the element referenced by position.
iterator
erase(const_iterator first, const_iterator last)
Removes the elements in the range [[]first, last).
Arena *
GetArena() const
Gets the arena on which this RepeatedPtrField stores its elements.

void RepeatedPtrField::RemoveLast()

Remove the last element in the array.

Ownership of the element is retained by the array.


void RepeatedPtrField::DeleteSubrange(
        int start,
        int num)

Delete elements with indices in the range [[]start .

. start+num-1]. Caution: implementation moves all elements with indices [[]start+num .. ]. Calling this routine inside a loop can cause quadratic behavior.


void RepeatedPtrField::Reserve(
        int new_size)

Reserve space to expand the field to at least the given size.

This only resizes the pointer array; it doesn't allocate any objects. If the array is grown, it will always be at least doubled in size.


Element ** RepeatedPtrField::mutable_data()

Gets the underlying array.

This pointer is possibly invalidated by any add or remove operation.


void RepeatedPtrField::Swap(
        RepeatedPtrField * other)

Swap entire contents with "other".

If they are on separate arenas, then copies data.


void RepeatedPtrField::UnsafeArenaSwap(
        RepeatedPtrField * other)

Swap entire contents with "other".

Caller should guarantee that either both fields are on the same arena or both are on the heap. Swapping between different arenas with this function is disallowed and is caught via GOOGLE_DCHECK.


void RepeatedPtrField::AddAllocated(
        Element * value)

Add an already-allocated object, passing ownership to the RepeatedPtrField.

Note that some special behavior occurs with respect to arenas:

(i) if this field holds submessages, the new submessage will be copied if
the original is in an arena and this RepeatedPtrField is either in a
different arena, or on the heap.
(ii) if this field holds strings, the passed-in string *must* be
heap-allocated, not arena-allocated. There is no way to dynamically check
this at runtime, so User Beware.

Element * RepeatedPtrField::ReleaseLast()

Remove the last element and return it, passing ownership to the caller.

Requires: size() > 0

If this RepeatedPtrField is on an arena, an object copy is required to pass ownership back to the user (for compatible semantics). UseUnsafeArenaReleaseLast() if this behavior is undesired.


void RepeatedPtrField::UnsafeArenaAddAllocated(
        Element * value)

Add an already-allocated object, skipping arena-ownership checks.

The user must guarantee that the given object is in the same arena as this RepeatedPtrField.


Element * RepeatedPtrField::UnsafeArenaReleaseLast()

Remove the last element and return it.

Works only when operating on an arena. The returned pointer is to the original object in the arena, hence has the arena's lifetime. Requires: current_size_ > 0


void RepeatedPtrField::ExtractSubrange(
        int start,
        int num,
        Element ** elements)

Extract elements with indices in the range "[[]start .. start+num-1]".

The caller assumes ownership of the extracted elements and is responsible for deleting them when they are no longer needed. If "elements" is non-NULL, then pointers to the extracted elements are stored in "elements[[]0 .. num-1]" for the convenience of the caller. If "elements" is NULL, then the caller must use some other mechanism to perform any further operations (like deletion) on these elements. Caution: implementation also moves elements with indices [[]start+num ..]. Calling this routine inside a loop can cause quadratic behavior.

Memory copying behavior is identical to ReleaseLast(), described above: if this RepeatedPtrField is on an arena, an object copy is performed for each returned element, so that all returned element pointers are to heap-allocated copies. If this copy is not desired, the user should callUnsafeArenaExtractSubrange().


void RepeatedPtrField::UnsafeArenaExtractSubrange(
        int start,
        int num,
        Element ** elements)

Identical to ExtractSubrange() described above, except that when this repeated field is on an arena, no object copies are performed.

Instead, the raw object pointers are returned. Thus, if on an arena, the returned objects must not be freed, because they will not be heap-allocated objects.


void RepeatedPtrField::AddCleared(
        Element * value)

Add an element to the pool of cleared objects, passing ownership to the RepeatedPtrField.

The element must be cleared prior to calling this method.

This method cannot be called when the repeated field is on an arena or when |value| is; both cases will trigger a GOOGLE_DCHECK-failure.


Element * RepeatedPtrField::ReleaseCleared()

Remove a single element from the cleared pool and return it, passing ownership to the caller.

The element is guaranteed to be cleared. Requires: ClearedCount() > 0

This method cannot be called when the repeated field is on an arena; doing so will trigger a GOOGLE_DCHECK-failure.

struct Metadata

#include <google/protobuf/message.h>
namespace google::protobuf

A container to hold message metadata.

Members

const Descriptor *
descriptor
const Reflection *
reflection

class Message: public MessageLite

#include <google/protobuf/message.h>
namespace google::protobuf

Abstract interface for protocol messages.

See also MessageLite, which contains most every-day operations. Message adds descriptors and reflection on top of that.

The methods of this class that are virtual but not pure-virtual have default implementations based on reflection. Message classes which are optimized for speed will want to override these with faster implementations, but classes optimized for code size may be happy with keeping them. See the optimize_for option in descriptor.proto.

Known subclasses:

Members

Message()
virtual
~Message()
protected virtualMetadata
GetMetadata() const = 0
Get a struct containing the metadata for the Messagemore...

Basic Operations

virtual Message*
New() const = 0
Construct a new instance of the same type. more...
virtual Message*
New(Arena * arena) const
Construct a new instance on the arena. more...
virtual void
CopyFrom(const Message & from)
Make this message into a copy of the given message. more...
virtual void
MergeFrom(const Message & from)
Merge the fields from the given message into this message. more...
void
CheckInitialized() const
Verifies that IsInitialized() returns true. more...
void
FindInitializationErrors(vector< string > * errors) const
Slowly build a list of all required fields that are not set. more...
virtual string
InitializationErrorString() const
Like FindInitializationErrors, but joins all the strings, delimited by commas, and returns them.
virtual void
DiscardUnknownFields()
Clears all unknown fields from this message and all embedded messages. more...
virtual int
SpaceUsed() const
Computes (an estimate of) the total number of bytes currently used for storing the message in memory. more...

Debugging & Testing

string
DebugString() const
Generates a human readable form of this message, useful for debugging and other purposes.
string
ShortDebugString() const
Like DebugString(), but with less whitespace.
string
Utf8DebugString() const
Like DebugString(), but do not escape UTF-8 byte sequences.
void
PrintDebugString() const
Convenience function useful in GDB. Prints DebugString() to stdout.

Heavy I/O

Additional parsing and serialization methods not implemented by MessageLite because they are not supported by the lite library.
bool
ParseFromFileDescriptor(int file_descriptor)
Parse a protocol buffer from a file descriptor. more...
bool
ParsePartialFromFileDescriptor(int file_descriptor)
Like ParseFromFileDescriptor(), but accepts messages that are missing required fields.
bool
ParseFromIstream(istream * input)
Parse a protocol buffer from a C++ istream. more...
bool
ParsePartialFromIstream(istream * input)
Like ParseFromIstream(), but accepts messages that are missing required fields.
bool
SerializeToFileDescriptor(int file_descriptor) const
Serialize the message and write it to the given file descriptor. more...
bool
SerializePartialToFileDescriptor(int file_descriptor) const
Like SerializeToFileDescriptor(), but allows missing required fields.
bool
SerializeToOstream(ostream * output) const
Serialize the message and write it to the given C++ ostream. more...
bool
SerializePartialToOstream(ostream * output) const
Like SerializeToOstream(), but allows missing required fields.

Reflection-based methods

These methods are pure-virtual in MessageLite, but Message provides reflection-based default implementations.
virtual string
GetTypeName() const
Get the name of this message type, e.g. "foo.bar.BazProto".
virtual void
Clear()
Clear all fields of the message and set them to their default values. more...
virtual bool
IsInitialized() const
Quickly check if all required fields have values set.
virtual void
CheckTypeAndMergeFrom(const MessageLite & other)
If |other| is the exact same class as this, calls MergeFrom()more...
virtual bool
MergePartialFromCodedStream(io::CodedInputStream * input)
Like MergeFromCodedStream(), but succeeds even if required fields are missing in the input. more...
virtual int
ByteSize() const
Computes the serialized size of the message. more...
virtual void
SerializeWithCachedSizes(io::CodedOutputStream * output) const
Serializes the message without recomputing the size. more...

Introspection

typedef
Typedef for backwards-compatibility.
constDescriptor *
GetDescriptor() const
Get a Descriptor for this message's type. more...
virtual constReflection *
GetReflection() const
Get the Reflection interface for this Message, which can be used to read and modify the fields of the Message dynamically (in other words, without knowing the message type at compile time). more...

protected virtual Metadata Message::GetMetadata() const = 0

Get a struct containing the metadata for the Message.

Most subclasses only need to implement this method, rather than the GetDescriptor() and GetReflection() wrappers.


virtual Message * Message::New() const = 0

Construct a new instance of the same type.

Ownership is passed to the caller. (This is also defined in MessageLite, but is defined again here for return-type covariance.)


virtual Message * Message::New(
        Arena * arena) const

Construct a new instance on the arena.

Ownership is passed to the caller if arena is a NULL. Default implementation allows for API compatibility during the Arena transition.


virtual void Message::CopyFrom(
        const Message & from)

Make this message into a copy of the given message.

The given message must have the same descriptor, but need not necessarily be the same class. By default this is just implemented as "Clear(); MergeFrom(from);".


virtual void Message::MergeFrom(
        const Message & from)

Merge the fields from the given message into this message.

Singular fields will be overwritten, if specified in from, except for embedded messages which will be merged. Repeated fields will be concatenated. The given message must be of the same type as this message (i.e. the exact same class).


void Message::CheckInitialized() const

Verifies that IsInitialized() returns true.

GOOGLE_CHECK-fails otherwise, with a nice error message.


void Message::FindInitializationErrors(
        vector< string > * errors) const

Slowly build a list of all required fields that are not set.

This is much, much slower than IsInitialized() as it is implemented purely via reflection. Generally, you should not call this unless you have already determined that an error exists by calling IsInitialized().


virtual void Message::DiscardUnknownFields()

Clears all unknown fields from this message and all embedded messages.

Normally, if unknown tag numbers are encountered when parsing a message, the tag and value are stored in the message's UnknownFieldSet and then written back out when the message is serialized. This allows servers which simply route messages to other servers to pass through messages that have new field definitions which they don't yet know about. However, this behavior can have security implications. To avoid it, call this method after parsing.

See Reflection::GetUnknownFields() for more on unknown fields.


virtual int Message::SpaceUsed() const

Computes (an estimate of) the total number of bytes currently used for storing the message in memory.

The default implementation calls the Reflection object's SpaceUsed() method.


bool Message::ParseFromFileDescriptor(
        int file_descriptor)

Parse a protocol buffer from a file descriptor.

If successful, the entire input will be consumed.


bool Message::ParseFromIstream(
        istream * input)

Parse a protocol buffer from a C++ istream.

If successful, the entire input will be consumed.


bool Message::SerializeToFileDescriptor(
        int file_descriptor) const

Serialize the message and write it to the given file descriptor.

All required fields must be set.


bool Message::SerializeToOstream(
        ostream * output) const

Serialize the message and write it to the given C++ ostream.

All required fields must be set.


virtual void Message::Clear()

Clear all fields of the message and set them to their default values.

Clear() avoids freeing memory, assuming that any memory allocated to hold parts of the message will be needed again to hold the next message. If you actually want to free the memory used by a Message, you must delete it.


virtual void Message::CheckTypeAndMergeFrom(
        const MessageLite & other)

If |other| is the exact same class as this, calls MergeFrom().

Otherwise, results are undefined (probably crash).


virtual bool Message::MergePartialFromCodedStream(
        io::CodedInputStream * input)

Like MergeFromCodedStream(), but succeeds even if required fields are missing in the input.

MergeFromCodedStream() is just implemented as MergePartialFromCodedStream() followed by IsInitialized().


virtual int Message::ByteSize() const

Computes the serialized size of the message.

This recursively calls ByteSize() on all embedded messages. If a subclass does not override this, it MUST override SetCachedSize().


virtual void Message::SerializeWithCachedSizes(
        io::CodedOutputStream * output) const

Serializes the message without recomputing the size.

The message must not have changed since the last call to ByteSize(); if it has, the results are undefined.


const Descriptor * 
    Message::GetDescriptor() const

Get a Descriptor for this message's type.

This describes what fields the message contains, the types of those fields, etc.


virtual const Reflection * 
    Message::GetReflection() const

Get the Reflection interface for this Message, which can be used to read and modify the fields of the Message dynamically (in other words, without knowing the message type at compile time).

This object remains property of the Message.

This method remains virtual in case a subclass does not implement reflection and wants to override the default behavior.

template class RepeatedFieldRef

#include <google/protobuf/message.h>
namespace google::protobuf

template

Forward-declare RepeatedFieldRef templates.

The second type parameter is used for SFINAE tricks. Users should ignore it.

Members

template class MutableRepeatedFieldRef

#include <google/protobuf/message.h>
namespace google::protobuf

template


Members

class Reflection

#include <google/protobuf/message.h>
namespace google::protobuf

This interface contains methods that can be used to dynamically access and modify the fields of a protocol message.

Their semantics are similar to the accessors the protocol compiler generates.

To get the Reflection for a given Message, call Message::GetReflection().

This interface is separate from Message only for efficiency reasons; the vast majority of implementations of Message will share the same implementation of Reflection (GeneratedMessageReflection, defined in generated_message.h), and all Messages of a particular class should share the same Reflection object (though you should not rely on the latter fact).

There are several ways that these methods can be used incorrectly. For example, any of the following conditions will lead to undefined results (probably assertion failures):

  • The FieldDescriptor is not a field of this message type.
  • The method called is not appropriate for the field's type. For each field type in FieldDescriptor::TYPE_*, there is only one Get*() method, one Set*() method, and one Add*() method that is valid for that type. It should be obvious which (except maybe for TYPE_BYTES, which are represented using strings in C++).
  • A Get*() or Set*() method for singular fields is called on a repeated field.
  • GetRepeated*(), SetRepeated*(), or Add*() is called on a non-repeated field.
  • The Message object passed to any method is not of the right type for this Reflection object (i.e. message.GetReflection() != reflection).

You might wonder why there is not any abstract representation for a field of arbitrary type. E.g., why isn't there just a "GetField()" method that returns "const Field&", where "Field" is some class with accessors like "GetInt32Value()". The problem is that someone would have to deal with allocating these Field objects. For generated message classes, having to allocate space for an additional object to wrap every field would at least double the message's memory footprint, probably worse. Allocating the objects on-demand, on the other hand, would be expensive and prone to memory leaks. So, instead we ended up with this flat interface.

TODO(kenton): Create a utility class which callers can use to read and write fields from a Reflection without paying attention to the type.

Members

Reflection()
virtual
~Reflection()
virtual const UnknownFieldSet &
GetUnknownFields(const Message & message) const = 0
Get the UnknownFieldSet for the message. more...
virtual UnknownFieldSet *
MutableUnknownFields(Message * message) const = 0
Get a mutable pointer to the UnknownFieldSet for the message. more...
virtual int
SpaceUsed(const Message & message) const = 0
Estimate the amount of memory used by the message object.
virtual bool
HasField(const Message & message, const FieldDescriptor * field) const = 0
Check if the given non-repeated field is set.
virtual int
FieldSize(const Message & message, const FieldDescriptor * field) const = 0
Get the number of elements of a repeated field.
virtual void
ClearField(Message * message, const FieldDescriptor * field) const = 0
Clear the value of a field, so that HasField() returns false or FieldSize() returns zero.
virtual bool
HasOneof(const Message & , const OneofDescriptor * ) const
Check if the oneof is set. more...
virtual void
ClearOneof(Message * , const OneofDescriptor * ) const
virtual const FieldDescriptor *
GetOneofFieldDescriptor(const Message & , const OneofDescriptor * ) const
Returns the field descriptor if the oneof is set. more...
virtual void
RemoveLast(Message * message, const FieldDescriptor * field) const = 0
Removes the last element of a repeated field. more...
virtual Message *
ReleaseLast(Message * message, const FieldDescriptor * field) const = 0
Removes the last element of a repeated message field, and returns the pointer to the caller. more...
virtual void
Swap(Message * message1, Message * message2) const = 0
Swap the complete contents of two messages.
virtual void
SwapFields(Message * message1, Message * message2, const vector< const FieldDescriptor * > & fields) const = 0
Swap fields listed in fields vector of two messages.
virtual void
SwapElements(Message * message, const FieldDescriptor * field, int index1, int index2) const = 0
Swap two elements of a repeated field.
virtual void
ListFields(const Message & message, vector< const FieldDescriptor * > * output) const = 0
List all fields of the message which are currently set. more...
const RepeatedPtrField< string > &
GetRepeatedPtrField(const Message & message, const FieldDescriptor * field) const
RepeatedPtrField< string > *
MutableRepeatedPtrField(Message * message, const FieldDescriptor * field) const
const RepeatedPtrFieldMessage> &
GetRepeatedPtrField(const Message & message, const FieldDescriptor * field) const
RepeatedPtrFieldMessage > *
MutableRepeatedPtrField(Message * message, const FieldDescriptor * field) const
template constRepeatedPtrField< PB > &
GetRepeatedPtrField(const Message & message, const FieldDescriptor * field) const
template RepeatedPtrField< PB > *
MutableRepeatedPtrField(Message * message, const FieldDescriptor * field) const
protected virtual void *
MutableRawRepeatedField(Message * message, const FieldDescriptor * field,FieldDescriptor::CppType , int ctype, const Descriptor * message_type) const = 0
Obtain a pointer to a Repeated Field Structure and do some type checking: more...
protected virtualMessageFactory *
GetMessageFactory() const
protected virtual void *
RepeatedFieldData(Message * message, const FieldDescriptor * field, FieldDescriptor::CppTypecpp_type, const Descriptor * message_type) const
Returns a raw pointer to the repeated field. more...
protected virtual const internal::RepeatedFieldAccessor *
RepeatedFieldAccessor(const FieldDescriptor * field) const
The returned pointer should point to a singleton instance which implements the RepeatedFieldAccessor interface.

Singular field getters

These get the value of a non-repeated field. They return the default value for fields that aren't set.
virtual int32
GetInt32(const Message & message, const FieldDescriptor * field) const = 0
virtual int64
GetInt64(const Message & message, const FieldDescriptor * field) const = 0
virtual uint32
GetUInt32(const Message & message, const FieldDescriptor * field) const = 0
virtual uint64
GetUInt64(const Message & message, const FieldDescriptor * field) const = 0
virtual float
GetFloat(const Message & message, const FieldDescriptor * field) const = 0
virtual double
GetDouble(const Message & message, const FieldDescriptor * field) const = 0
virtual bool
GetBool(const Message & message, const FieldDescriptor * field) const = 0
virtual string
GetString(const Message & message, const FieldDescriptor * field) const = 0
virtual constEnumValueDescriptor *
GetEnum(const Message & message, const FieldDescriptor * field) const = 0
virtual int
GetEnumValue(const Message & message, const FieldDescriptor * field) const
GetEnumValue() returns an enum field's value as an integer rather than an EnumValueDescriptor*. more...
virtual const Message &
GetMessage(const Message & message, const FieldDescriptor * field, MessageFactory * factory = NULL) const = 0
See MutableMessage() for the meaning of the "factory" parameter.
virtual const string &
GetStringReference(const Message & message, const FieldDescriptor * field, string * scratch) const = 0
Get a string value without copying, if possible. more...

Singular field mutators

These mutate the value of a non-repeated field.
virtual void
SetInt32(Message * message, const FieldDescriptor * field, int32 value) const = 0
virtual void
SetInt64(Message * message, const FieldDescriptor * field, int64 value) const = 0
virtual void
SetUInt32(Message * message, const FieldDescriptor * field, uint32 value) const = 0
virtual void
SetUInt64(Message * message, const FieldDescriptor * field, uint64 value) const = 0
virtual void
SetFloat(Message * message, const FieldDescriptor * field, float value) const = 0
virtual void
SetDouble(Message * message, const FieldDescriptor * field, double value) const = 0
virtual void
SetBool(Message * message, const FieldDescriptor * field, bool value) const = 0
virtual void
SetString(Message * message, const FieldDescriptor * field, const string & value) const = 0
virtual void
SetEnum(Message * message, const FieldDescriptor * field, const EnumValueDescriptor * value) const = 0
virtual void
SetEnumValue(Message * message, const FieldDescriptor * field, int value) const
Set an enum field's value with an integer rather than EnumValueDescriptormore...
virtual Message *
MutableMessage(Message * message, const FieldDescriptor * field, MessageFactory * factory = NULL) const = 0
Get a mutable pointer to a field with a message type. more...
virtual void
SetAllocatedMessage(Message * message, Message * sub_message, const FieldDescriptor * field) const = 0
Replaces the message specified by 'field' with the already-allocated object sub_message, passing ownership to the message. more...
virtual Message *
ReleaseMessage(Message * message, const FieldDescriptor * field, MessageFactory * factory = NULL) const = 0
Releases the message specified by 'field' and returns the pointer, ReleaseMessage() will return the message the message object if it exists. more...

Repeated field getters

These get the value of one element of a repeated field.
virtual int32
GetRepeatedInt32(const Message & message, const FieldDescriptor * field, int index) const = 0
virtual int64
GetRepeatedInt64(const Message & message, const FieldDescriptor * field, int index) const = 0
virtual uint32
GetRepeatedUInt32(const Message & message, const FieldDescriptor * field, int index) const = 0
virtual uint64
GetRepeatedUInt64(const Message & message, const FieldDescriptor * field, int index) const = 0
virtual float
GetRepeatedFloat(const Message & message, const FieldDescriptor * field, int index) const = 0
virtual double
GetRepeatedDouble(const Message & message, const FieldDescriptor * field, int index) const = 0
virtual bool
GetRepeatedBool(const Message & message, const FieldDescriptor * field, int index) const = 0
virtual string
GetRepeatedString(const Message & message, const FieldDescriptor * field, int index) const = 0
virtual constEnumValueDescriptor *
GetRepeatedEnum(const Message & message, const FieldDescriptor * field, int index) const = 0
virtual int
GetRepeatedEnumValue(const Message & message, const FieldDescriptor * field, int index) const
GetRepeatedEnumValue() returns an enum field's value as an integer rather than an EnumValueDescriptor*. more...
virtual const Message &
GetRepeatedMessage(const Message & message, const FieldDescriptor * field, int index) const = 0
virtual const string &
GetRepeatedStringReference(const Message & message, const FieldDescriptor * field, int index, string * scratch) const = 0
See GetStringReference(), above.

Repeated field mutators

These mutate the value of one element of a repeated field.
virtual void
SetRepeatedInt32(Message * message, const FieldDescriptor * field, int index, int32 value) const = 0
virtual void
SetRepeatedInt64(Message * message, const FieldDescriptor * field, int index, int64 value) const = 0
virtual void
SetRepeatedUInt32(Message * message, const FieldDescriptor * field, int index, uint32 value) const = 0
virtual void
SetRepeatedUInt64(Message * message, const FieldDescriptor * field, int index, uint64 value) const = 0
virtual void
SetRepeatedFloat(Message * message, const FieldDescriptor * field, int index, float value) const = 0
virtual void
SetRepeatedDouble(Message * message, const FieldDescriptor * field, int index, double value) const = 0
virtual void
SetRepeatedBool(Message * message, const FieldDescriptor * field, int index, bool value) const = 0
virtual void
SetRepeatedString(Message * message, const FieldDescriptor * field, int index, const string & value) const = 0
virtual void
SetRepeatedEnum(Message * message, const FieldDescriptor * field, int index, constEnumValueDescriptor * value) const = 0
virtual void
SetRepeatedEnumValue(Message * message, const FieldDescriptor * field, int index, int value) const
Set an enum field's value with an integer rather than EnumValueDescriptormore...
virtual Message *
MutableRepeatedMessage(Message * message, const FieldDescriptor * field, int index) const = 0
Get a mutable pointer to an element of a repeated field with a message type.

Repeated field adders

These add an element to a repeated field.
virtual void
AddInt32(Message * message, const FieldDescriptor * field, int32 value) const = 0
virtual void
AddInt64(Message * message, const FieldDescriptor * field, int64 value) const = 0
virtual void
AddUInt32(Message * message, const FieldDescriptor * field, uint32 value) const = 0
virtual void
AddUInt64(Message * message, const FieldDescriptor * field, uint64 value) const = 0
virtual void
AddFloat(Message * message, const FieldDescriptor * field, float value) const = 0
virtual void
AddDouble(Message * message, const FieldDescriptor * field, double value) const = 0
virtual void
AddBool(Message * message, const FieldDescriptor * field, bool value) const = 0
virtual void
AddString(Message * message, const FieldDescriptor * field, const string & value) const = 0
virtual void
AddEnum(Message * message, const FieldDescriptor * field, const EnumValueDescriptor * value) const = 0
virtual void
AddEnumValue(Message * message, const FieldDescriptor * field, int value) const
Set an enum field's value with an integer rather than EnumValueDescriptormore...
virtual Message *
AddMessage(Message * message, const FieldDescriptor * field, MessageFactory * factory = NULL) const = 0
See MutableMessage() for comments on the "factory" parameter.
template RepeatedFieldRef< T >
GetRepeatedFieldRef(const Message & message, const FieldDescriptor * field) const
Get a RepeatedFieldRef object that can be used to read the underlying repeated field. more...
templateMutableRepeatedFieldRef< T >
GetMutableRepeatedFieldRef(Message * message, const FieldDescriptor * field) const
Like GetRepeatedFieldRef() but return an object that can also be used manipulate the underlying repeated field.
template const RepeatedField< T > &
GetRepeatedField(const Message & , const FieldDescriptor * ) const
DEPRECATED. more...
template RepeatedField< T > *
MutableRepeatedField(Message * , const FieldDescriptor * ) const
DEPRECATED. more...
template constRepeatedPtrField< T > &
GetRepeatedPtrField(const Message & , const FieldDescriptor * ) const
DEPRECATED. more...
template RepeatedPtrField< T > *
MutableRepeatedPtrField(Message * , const FieldDescriptor * ) const
DEPRECATED. more...

Extensions

virtual const FieldDescriptor *
FindKnownExtensionByName(const string & name) const = 0
Try to find an extension of this message type by fully-qualified field name. more...
virtual const FieldDescriptor *
FindKnownExtensionByNumber(int number) const = 0
Try to find an extension of this message type by field number. more...

Feature Flags

virtual bool
SupportsUnknownEnumValues() const
Does this message support storing arbitrary integer values in enum fields? If |true|, GetEnumValue/SetEnumValue and associated repeated-field versions take arbitrary integer values, and the legacy GetEnum() getter will dynamically create an EnumValueDescriptor for any integer value without one.more...

virtual const UnknownFieldSet & 
    Reflection::GetUnknownFields(
        const Message & message) const = 0

Get the UnknownFieldSet for the message.

This contains fields which were seen when the Message was parsed but were not recognized according to the Message's definition. For proto3 protos, this method will always return an empty UnknownFieldSet.


virtual UnknownFieldSet * 
    Reflection::MutableUnknownFields(
        Message * message) const = 0

Get a mutable pointer to the UnknownFieldSet for the message.

This contains fields which were seen when the Message was parsed but were not recognized according to the Message's definition. For proto3 protos, this method will return a valid mutable UnknownFieldSet pointer but modifying it won't affect the serialized bytes of the message.


virtual bool Reflection::HasOneof(
        const Message & ,
        const OneofDescriptor * ) const

Check if the oneof is set.

Returns true if any field in oneof is set, false otherwise. TODO(jieluo) - make it pure virtual after updating all the subclasses.


virtual const FieldDescriptor * 
    Reflection::GetOneofFieldDescriptor(
        const Message & ,
        const OneofDescriptor * ) const

Returns the field descriptor if the oneof is set.

NULL otherwise. TODO(jieluo) - make it pure virtual.


virtual void Reflection::RemoveLast(
        Message * message,
        const FieldDescriptor * field) const = 0

Removes the last element of a repeated field.

We don't provide a way to remove any element other than the last because it invites inefficient use, such as O(n^2) filtering loops that should have been O(n). If you want to remove an element other than the last, the best way to do it is to re-arrange the elements (using Swap()) so that the one you want removed is at the end, then call RemoveLast().


virtual Message * Reflection::ReleaseLast(
        Message * message,
        const FieldDescriptor * field) const = 0

Removes the last element of a repeated message field, and returns the pointer to the caller.

Caller takes ownership of the returned pointer.


virtual void Reflection::ListFields(
        const Message & message,
        vector< const FieldDescriptor * > * output) const = 0

List all fields of the message which are currently set.

This includes extensions. Singular fields will only be listed if HasField(field) would return true and repeated fields will only be listed if FieldSize(field) would return non-zero. Fields (both normal fields and extension fields) will be listed ordered by field number.


protected virtual void * Reflection::MutableRawRepeatedField(
        Message * message,
        const FieldDescriptor * field,
        FieldDescriptor::CppType ,
        int ctype,
        const Descriptor * message_type) const = 0

Obtain a pointer to a Repeated Field Structure and do some type checking:

on field->cpp_type(),
on field->field_option().ctype() (if ctype >= 0)
of field->message_type() (if message_type != NULL).

We use 1 routine rather than 4 (const vs mutable) x (scalar vs pointer).


protected virtual void * Reflection::RepeatedFieldData(
        Message * message,
        const FieldDescriptor * field,
        FieldDescriptor::CppType cpp_type,
        const Descriptor * message_type) const

Returns a raw pointer to the repeated field.

"cpp_type" and "message_type" are decuded from the type parameter T passed to Get(Mutable)RepeatedFieldRef. If T is a generated message type, "message_type" should be set to its descriptor. Otherwise "message_type" should be set to NULL. Implementations of this method should check whether "cpp_type"/"message_type" is consistent with the actual type of the field.


virtual int Reflection::GetEnumValue(
        const Message & message,
        const FieldDescriptor * field) const

GetEnumValue() returns an enum field's value as an integer rather than an EnumValueDescriptor*.

If the integer value does not correspond to a known value descriptor, a new value descriptor is created. (Such a value will only be present when the new unknown-enum-value semantics are enabled for a message.)


virtual const string & Reflection::GetStringReference(
        const Message & message,
        const FieldDescriptor * field,
        string * scratch) const = 0

Get a string value without copying, if possible.

GetString() necessarily returns a copy of the string. This can be inefficient when the string is already stored in a string object in the underlying message. GetStringReference() will return a reference to the underlying string in this case. Otherwise, it will copy the string into *scratch and return that.

Note: It is perfectly reasonable and useful to write code like:

str = reflection->GetStringReference(field, &str);

This line would ensure that only one copy of the string is made regardless of the field's underlying representation. When initializing a newly-constructed string, though, it's just as fast and more readable to use code like:

string str = reflection->GetString(field);

virtual void Reflection::SetEnumValue(
        Message * message,
        const FieldDescriptor * field,
        int value) const

Set an enum field's value with an integer rather than EnumValueDescriptor.

If the value does not correspond to a known enum value, either behavior is undefined (for proto2 messages), or the value is accepted silently for messages with new unknown-enum-value semantics.


virtual Message * Reflection::MutableMessage(
        Message * message,
        const FieldDescriptor * field,
        MessageFactory * factory = NULL) const = 0

Get a mutable pointer to a field with a message type.

If a MessageFactory is provided, it will be used to construct instances of the sub-message; otherwise, the default factory is used. If the field is an extension that does not live in the same pool as the containing message's descriptor (e.g. it lives in an overlay pool), then a MessageFactory must be provided. If you have no idea what that meant, then you probably don't need to worry about it (don't provide a MessageFactory). WARNING: If the FieldDescriptor is for a compiled-in extension, then factory->GetPrototype(field->message_type() MUST return an instance of the compiled-in class for this type, NOT DynamicMessage.


virtual void Reflection::SetAllocatedMessage(
        Message * message,
        Message * sub_message,
        const FieldDescriptor * field) const = 0

Replaces the message specified by 'field' with the already-allocated object sub_message, passing ownership to the message.

If the field contained a message, that message is deleted. If sub_message is NULL, the field is cleared.


virtual Message * Reflection::ReleaseMessage(
        Message * message,
        const FieldDescriptor * field,
        MessageFactory * factory = NULL) const = 0

Releases the message specified by 'field' and returns the pointer, ReleaseMessage() will return the message the message object if it exists.

Otherwise, it may or may not return NULL. In any case, if the return value is non-NULL, the caller takes ownership of the pointer. If the field existed (HasField() is true), then the returned pointer will be the same as the pointer returned by MutableMessage(). This function has the same effect asClearField().


virtual int Reflection::GetRepeatedEnumValue(
        const Message & message,
        const FieldDescriptor * field,
        int index) const

GetRepeatedEnumValue() returns an enum field's value as an integer rather than an EnumValueDescriptor*.

If the integer value does not correspond to a known value descriptor, a new value descriptor is created. (Such a value will only be present when the new unknown-enum-value semantics are enabled for a message.)


virtual void Reflection::SetRepeatedEnumValue(
        Message * message,
        const FieldDescriptor * field,
        int index,
        int value) const

Set an enum field's value with an integer rather than EnumValueDescriptor.

If the value does not correspond to a known enum value, either behavior is undefined (for proto2 messages), or the value is accepted silently for messages with new unknown-enum-value semantics.


virtual void Reflection::AddEnumValue(
        Message * message,
        const FieldDescriptor * field,
        int value) const

Set an enum field's value with an integer rather than EnumValueDescriptor.

If the value does not correspond to a known enum value, either behavior is undefined (for proto2 messages), or the value is accepted silently for messages with new unknown-enum-value semantics.


template RepeatedFieldRef< T > 
    Reflection::GetRepeatedFieldRef(
        const Message & message,
        const FieldDescriptor * field) const

Get a RepeatedFieldRef object that can be used to read the underlying repeated field.

The type parameter T must be set according to the field's cpp type. The following table shows the mapping from cpp type to acceptable T.

field->cpp_type()      T
CPPTYPE_INT32        int32
CPPTYPE_UINT32       uint32
CPPTYPE_INT64        int64
CPPTYPE_UINT64       uint64
CPPTYPE_DOUBLE       double
CPPTYPE_FLOAT        float
CPPTYPE_BOOL         bool
CPPTYPE_ENUM         generated enum type or int32
CPPTYPE_STRING       string
CPPTYPE_MESSAGE      generated message type or google::protobuf::Message
  A RepeatedFieldRef object can be copied and the resulted object will point
  to the same repeated field in the same message. The object can be used as
  long as the message is not destroyed.

  Note that to use this method users need to include the header file
  "google/protobuf/reflection.h" (which defines the RepeatedFieldRef
  class templates).  

template const RepeatedField< T > & 
    Reflection::GetRepeatedField(
        const Message & ,
        const FieldDescriptor * ) const

DEPRECATED.

Please use GetRepeatedFieldRef().

for T = Cord and all protobuf scalar types except enums.


template RepeatedField< T > * 
    Reflection::MutableRepeatedField(
        Message * ,
        const FieldDescriptor * ) const

DEPRECATED.

Please use GetMutableRepeatedFieldRef().

for T = Cord and all protobuf scalar types except enums.


template const RepeatedPtrField< T > & 
    Reflection::GetRepeatedPtrField(
        const Message & ,
        const FieldDescriptor * ) const

DEPRECATED.

Please use GetRepeatedFieldRef().

 for T = string, google::protobuf::internal::StringPieceField
google::protobuf::Message & descendants.

template RepeatedPtrField< T > * 
    Reflection::MutableRepeatedPtrField(
        Message * ,
        const FieldDescriptor * ) const

DEPRECATED.

Please use GetMutableRepeatedFieldRef().

 for T = string, google::protobuf::internal::StringPieceField
google::protobuf::Message & descendants.

virtual const FieldDescriptor * 
    Reflection::FindKnownExtensionByName(
        const string & name) const = 0

Try to find an extension of this message type by fully-qualified field name.

Returns NULL if no extension is known for this name or number.


virtual const FieldDescriptor * 
    Reflection::FindKnownExtensionByNumber(
        int number) const = 0

Try to find an extension of this message type by field number.

Returns NULL if no extension is known for this name or number.


virtual bool Reflection::SupportsUnknownEnumValues() const

Does this message support storing arbitrary integer values in enum fields? If |true|, GetEnumValue/SetEnumValue and associated repeated-field versions take arbitrary integer values, and the legacy GetEnum() getter will dynamically create an EnumValueDescriptor for any integer value without one.

If |false|, setting an unknown enum value via the integer-based setters results in undefined behavior (in practice, GOOGLE_DCHECK-fails).

Generic code that uses reflection to handle messages with enum fields should check this flag before using the integer-based setter, and either downgrade to a compatible value or use the UnknownFieldSet if not. For example:

int new_value = GetValueFromApplicationLogic(); if (reflection->SupportsUnknownEnumValues()) {

reflection->SetEnumValue(message, field, new_value);

} else {

if (field_descriptor->enum_type()->
        FindValueByNumver(new_value) != NULL) {
    reflection->SetEnumValue(message, field, new_value);
} else if (emit_unknown_enum_values) {
    reflection->MutableUnknownFields(message)->AddVarint(
        field->number(),
        new_value);
} else {
    // convert value to a compatible/default value.
    new_value = CompatibleDowngrade(new_value);
    reflection->SetEnumValue(message, field, new_value);
}

}

class MessageFactory

#include <google/protobuf/message.h>
namespace google::protobuf

Abstract interface for a factory for message objects.

Known subclasses:

Members

MessageFactory()
virtual
~MessageFactory()
virtual const Message *
GetPrototype(const Descriptor * type) = 0
Given a Descriptor, gets or constructs the default (prototype) Message of that type. more...
static MessageFactory *
generated_factory()
Gets a MessageFactory which supports all generated, compiled-in messages. more...
static void
InternalRegisterGeneratedFile(const char * filename, void(*)(const string &) register_messages)
For internal use only: Registers a .proto file at static initialization time, to be placed in generated_factory. more...
static void
InternalRegisterGeneratedMessage(const Descriptor * descriptor, const Message * prototype)
For internal use only: Registers a message type. more...

virtual const Message * MessageFactory::GetPrototype(
        const Descriptor * type) = 0

Given a Descriptor, gets or constructs the default (prototype) Message of that type.

You can then call that message's New() method to construct a mutable message of that type.

Calling this method twice with the same Descriptor returns the same object. The returned object remains property of the factory. Also, any objects created by calling the prototype's New() method share some data with the prototype, so these must be destroyed before the MessageFactory is destroyed.

The given descriptor must outlive the returned message, and hence must outlive the MessageFactory.

Some implementations do not support all types. GetPrototype() will return NULL if the descriptor passed in is not supported.

This method may or may not be thread-safe depending on the implementation. Each implementation should document its own degree thread-safety.


static MessageFactory * MessageFactory::generated_factory()

Gets a MessageFactory which supports all generated, compiled-in messages.

In other words, for any compiled-in type FooMessage, the following is true:

MessageFactory::generated_factory()->GetPrototype(
  FooMessage::descriptor()) == FooMessage::default_instance()

This factory supports all types which are found in DescriptorPool::generated_pool(). If given a descriptor from any other pool, GetPrototype() will return NULL. (You can also check if a descriptor is for a generated message by checking if descriptor->file()->pool() ==DescriptorPool::generated_pool().)

This factory is 100% thread-safe; calling GetPrototype() does not modify any shared data.

This factory is a singleton. The caller must not delete the object.


static void MessageFactory::InternalRegisterGeneratedFile(
        const char * filename,
        void(*)(const string &) register_messages)

For internal use only: Registers a .proto file at static initialization time, to be placed in generated_factory.

The first time GetPrototype() is called with a descriptor from this file, |register_messages| will be called, with the file name as the parameter. It must call InternalRegisterGeneratedMessage() (below) to register each message type in the file. This strange mechanism is necessary because descriptors are built lazily, so we can't register types by their descriptor until we know that the descriptor exists. |filename| must be a permanent string.


static void MessageFactory::InternalRegisterGeneratedMessage(
        const Descriptor * descriptor,
        const Message * prototype)

For internal use only: Registers a message type.

Called only by the functions which are registered with InternalRegisterGeneratedFile(), above.

阅读(5637) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

逃之夭夭new2019-09-04 08:01:24

你好,请问这些文档的官方路径是什么,能提供一下吗,多谢