我正在一个Python项目中使用Protobuf(v3.5.1)。我的情况可以简化为以下内容:
// Proto file
syntax = "proto3";
message Foo {
Bar bar = 1;
}
message Bar {
bytes lotta_bytes_here = 1;
}
# Python excerpt
def MakeFooUsingBar(bar):
foo = Foo()
foo.bar.CopyFrom(bar)
我担心.CopyFrom()
的内存性能(如果我没记错,它是在复制内容而不是引用)。在C++中,我可以使用类似以下的语句:
Foo foo;
Bar* bar = new Bar();
bar->set_lotta_bytes_here("abcd");
foo.set_allocated_bar(bar);
从生成的源代码来看,似乎不需要复制任何内容:
inline void Foo::set_allocated_bar(::Bar* bar) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
delete bar_;
}
if (bar) {
::google::protobuf::Arena* submessage_arena = NULL;
if (message_arena != submessage_arena) {
bar = ::google::protobuf::internal::GetOwnedMessage(
message_arena, bar, submessage_arena);
}
} else {
}
bar_ = bar;
// @@protoc_insertion_point(field_set_allocated:Foo.bar)
}
有没有类似的Python库可用?我已经查看了Python生成的源代码,但没有找到适用的内容。