thrift序列化和反序列化

thrift序列化和反序列化很简单,写个例子如下:

#include <transport/TSocket.h>  
#include <transport/TBufferTransports.h>  
#include <protocol/TBinaryProtocol.h>  

#include "gen-cpp/student_types.h"

using namespace apache::thrift;  
using namespace apache::thrift::protocol;  
using namespace apache::thrift::transport;  
  
using boost::shared_ptr; 

int main()
{
  // student的结构来自http://blog.csdn.net/hbuxiaoshe/article/details/6558391中的thrift
  Student s1;
  s1.__set_sno(1);
  s1.__set_sname("Hello");
  s1.__set_ssex(false);
  s1.__set_sage(21);

  // 序列化
  uint8_t* buf_ptr;
  uint32_t sz;
  shared_ptr<TMemoryBuffer> mem_buf(new TMemoryBuffer);
  shared_ptr<TBinaryProtocol> bin_proto(new TBinaryProtocol(mem_buf));
  s1.write(bin_proto.get());
  mem_buf->getBuffer(&buf_ptr, &sz);

  // 反序列化
  Student s2;
  shared_ptr<TMemoryBuffer> membuffer(new TMemoryBuffer());
  shared_ptr<TProtocol> protocol(new TBinaryProtocol(membuffer));
  membuffer->resetBuffer(buf_ptr, sz);
  s2.read(protocol.get());
  printf("%d %s %d %d\n", s2.sno, s2.sname.c_str(), s2.ssex, s2.sage);

  return 0;
}
编译命令:

g++ -g -o s s.cpp gen-cpp/student_constants.cpp gen-cpp/student_types.cpp \
-Lxxx/lib -Ixxx//include/thrift -lthrift

序列化还可以这样实现:

sz = s1.write(bin_proto.get());

string buf = mem_buf->getBufferAsString();


具体使用可查看TMemoryBuffer的接口,在文件include/thrift/transport/TBufferTransports.h中。


补充个易用模版:

#ifndef SERIALIZE_H_
#define SERIALIZE_H_

#include <config.h>
#include <protocol/TBinaryProtocol.h>
#include <transport/TTransportUtils.h>

template<typename ThriftStruct>
std::string ThriftToString(const ThriftStruct& ts) {
  using namespace apache::thrift::transport;  // NOLINT
  using namespace apache::thrift::protocol;  // NOLINT
  TMemoryBuffer* buffer = new TMemoryBuffer;
  boost::shared_ptr<TTransport> trans(buffer);
  TBinaryProtocol protocol(trans);
  ts.write(&protocol);
  uint8_t* buf;
  uint32_t size;
  buffer->getBuffer(&buf, &size);
  return std::string((char*)buf, (unsigned int)size);  // NOLINT
}

template<typename ThriftStruct>
bool StringToThrift(const std::string& buff,
                    ThriftStruct* ts) {
  using namespace apache::thrift::transport;  // NOLINT
  using namespace apache::thrift::protocol;  // NOLINT
  TMemoryBuffer* buffer = new TMemoryBuffer;
  buffer->write((const uint8_t*)buff.data(), buff.size());
  boost::shared_ptr<TTransport> trans(buffer);
  TBinaryProtocol protocol(trans);
  ts->read(&protocol);
  return true;
}

#endif  // SERIALIZE_H_



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值