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_