简体   繁体   English

Protobuf动态和静态库

[英]Protobuf dynamic and static library

I have two custom protobuf libraries. 我有两个自定义的protobuf库。 One is dynamic, other is static. 一种是动态的,另一种是静态的。 Static lib has a message: 静态库有一条消息:

message DataType
{
    int number = 1;
    string name_1 = 2;
    string name_2 = 3;
    string name_3 = 4;
}

// The dynamic lib has a message:
message MyMessage
{
    DataType type = 1;
}

I build dynamic proto lib with linking static proto lib to it. 我通过将静态原型库链接到它来构建动态原型库。 Then I build exe application to which I link dynamic proto lib. 然后,我建立了链接动态原型库的exe应用程序。

The problem is that when I set one of name_1, name_2 or name_3, they all have this value. 问题是当我设置name_1,name_2或name_3之一时,它们都具有此值。 I think all these strings have same buffer. 我认为所有这些字符串都具有相同的缓冲区。 If to convert dynamic lib to static, then problem disappears. 如果将动态库转换为静态库,则问题消失。 Could anyone explain me what is wrong with it? 谁能解释我这是怎么回事? Thank you. 谢谢。

If a field is not set then it should return empty string. 如果未设置字段,则应返回空字符串。 Please check the documentation here . 请在此处检查文档。

If you are using version 2 you can query whether the field is set by has_name_x() . 如果您使用的是版本2,则可以查询该字段是否由has_name_x()设置。

By the way there are several ways to set a value: 顺便说一下,有几种设置值的方法:

  • The simplest creates a copy: void set_name_x(const string& value) 最简单的方法是创建一个副本: void set_name_x(const string& value)
  • In case of C++11 you can move a string value: void set_name_x(string&& value) 对于C++11 ,可以移动字符串值: void set_name_x(string&& value)
  • You can pass pointer: void set_allocated_name_x(string* value) 您可以传递指针: void set_allocated_name_x(string* value)
  • You can get the pointer to the stored string: string* mutable_name_x() 您可以获取指向存储的字符串的指针: string* mutable_name_x()

I would advice to get familiar with protobuf and let it manage memory and use set_name_x . 我建议您熟悉protobuf并让其管理内存并使用set_name_x If it is not sufficient you can optimize your code with manual memory management. 如果这还不够,您可以使用手动内存管理来优化代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM