2013-10-30 27 views
3

我在序列化数据时遇到了很多麻烦。我究竟做错了什么?C++中的Apache Thrift序列化

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中,然后将其写入内存缓冲区中的写入方法。然后,我将该缓冲区作为一个字符串返回。然后,我会将序列化的字符串写入磁盘。

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节俭1.0-dev的,C++ 98如果这些东西有所作为:

我得到这个错误:

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

除了此说明。

回答

1

在C++中,你可以使用TFileTransport和您所选择的储蓄协议,即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(filename.c_str(), O_CREAT|O_TRUNC|O_WRONLY, 0666); // create file 

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

2

的ThriftObject.write()函数期望类型

apache::thrift::protocol::TProtocol* 

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

shared_ptr<TBinaryProtocol> protocolOut 

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

obj.write(protocolOut.get()); 

应该解决这个问题

+0

与信息更新答案 –