【问题标题】:Apache Thrift serialization in C++C++ 中的 Apache Thrift 序列化
【发布时间】:2017-02-01 08:37:33
【问题描述】:

我在序列化数据时遇到了很多麻烦。我做错了什么?

std::string serialize(ContactsList& obj, std::string filename) {
    shared_ptr<TMemoryBuffer> transportOut(new TMemoryBuffer());
    shared_ptr<TBinaryProtocol> protocolOut(new TBinaryProtocol(transportOut));
    obj.write(protocolOut);
    std::string serialized_string = transportOut->getBufferAsString();
    return serialized_string;
}

这是我从另一个方法调用的方法。我希望得到一个序列化的二进制字符串,我可以将其写入磁盘。在这个序列化方法中,我创建了一个 TMemory 缓冲区,然后我将它包装在一个 TBinaryProtocol 中,然后是对象的 write 方法,它将自己写入内存缓冲区。然后,我将该缓冲区作为字符串返回。然后我会将序列化的字符串写入磁盘。

我收到此错误:

error: no matching function for call to ‘addressbook::ContactsList::write(boost::shared_ptr<apache::thrift::protocol::TBinaryProtocolT<apache::thrift::transport::TTransport> >&)

还有这个注释:

note: no known conversion for argument 1 from ‘boost::shared_ptr<apache::thrift::protocol::TBinaryProtocolT<apache::thrift::transport::TTransport> >’ to ‘apache::thrift::protocol::TProtocol*

我正在使用 Apache Thrift 1.0-dev、C++ 98,如果这些东西有所作为的话。

【问题讨论】:

    标签: c++ serialization thrift


    【解决方案1】:

    ThriftObject.write() 函数需要一个类型的参数

    apache::thrift::protocol::TProtocol*
    

    即TProtocol 类型的“原始”指针。这里使用的protocolOut对象是类型的共享指针。

    shared_ptr<TBinaryProtocol> protocolOut
    

    shared_ptr 的 'get()' 方法给出了由 shared_ptr 对象管理的原始指针。 因此使用

    obj.write(protocolOut.get());
    

    应该解决问题

    【讨论】:

    • 更新了详细答案
    【解决方案2】:

    在 c++ 中,您可以使用 TFileTransport 和您选择的 Thrift 协议,即 TBinaryProtocol:

    shared_ptr<TFileTransport> transport(new TFileTransport(filename));
    shared_ptr<TBinaryProtocol> protocol(new TBinaryProtocol(transport));
    yourObj.write(protocol.get()); // to write
    

    yourObj.read(protocol.get()); // to read
    

    要确保文件存在,您可以使用 open before:

    open(filename.c_str(), O_CREAT|O_TRUNC|O_WRONLY, 0666); // create file
    

    ps.:实际上在所有其他目标语言中都非常相似。

    【讨论】:

      猜你喜欢
      • 2015-06-07
      • 2016-03-24
      • 2013-09-16
      • 1970-01-01
      • 2016-12-08
      • 2017-08-09
      • 2019-08-11
      • 1970-01-01
      • 2012-09-01
      相关资源
      最近更新 更多