假设我有两个类:
class1 {
int m_i;
std::string m_s;
};
class2 {
int m_i2;
class1 *m_ptr;
};现在,我想通过网络发送一个class2变量,并希望使用任何执行序列化的库。(Protocol-buffers、Thrift、MessagePack..)
我可以使用哪一个?(注意class1* m_ptr)
发布于 2012-07-15 00:01:41
使用google protocol buffers时,您需要一个.proto文件(比如test.proto),如下所示:
package serialisation; // puts this in namespace serialisation
message class1 {
required int32 m_i = 1;
required bytes m_s = 2;
}
message class2 {
required int32 m_i2 = 1;
optional class1 m_ptr = 2;
}使用C++,一旦对此运行protoc编译器,就会得到test.pb.cc和test.pb.h。
然后,您可以像这样使用它们:
#include <string>
#include "test.pb.h"
struct class1 {
int m_i;
std::string m_s;
};
struct class2 {
int m_i2;
class1 *m_ptr;
};
int main() {
class2 second_class;
second_class.m_i2 = 2;
second_class.m_ptr = new class1;
second_class.m_ptr->m_i = 1;
second_class.m_ptr->m_s = "one";
// Serialise class 2
serialisation::class2 serialisable_second_class;
serialisable_second_class.set_m_i2(second_class.m_i2);
if (second_class.m_ptr) {
serialisation::class1* serialisable_first_class = serialisable_second_class.mutable_m_ptr();
serialisable_first_class->set_m_i(second_class.m_ptr->m_i);
serialisable_first_class->set_m_s(second_class.m_ptr->m_s);
}
std::string serialised(serialisable_second_class.SerializeAsString());
// Parse class 2
serialisation::class2 parsed_second_class;
parsed_second_class.ParseFromString(serialised);
class2 retrieved_second_class;
retrieved_second_class.m_i2 = parsed_second_class.m_i2();
if (parsed_second_class.has_m_ptr()) {
retrieved_second_class.m_ptr = new class1;
retrieved_second_class.m_ptr->m_i = parsed_second_class.m_ptr().m_i();
retrieved_second_class.m_ptr->m_s = parsed_second_class.m_ptr().m_s();
} else {
retrieved_second_class.m_ptr = nullptr;
}
return 0;
}注意,为了简洁起见,我在这里不做任何错误检查或异常处理-这在生产代码中是需要的。我也没有管理class1指针的生命周期。
发布于 2012-07-14 19:43:01
你可以用节俭来做这件事。这个定义看起来像这样
struct class1 {
1: required i32 m_i;
2: required string m_s;
}
struct class2 {
1: required i32 m_i2;
2: optional class1 m_ptr;
}你想读这本优秀的指南吗?
http://diwakergupta.github.com/thrift-missing-guide/
为了弄清楚你在问题中提到的“指针”问题,请阅读“嵌套结构是如何初始化的?”在上面的指南中。
https://stackoverflow.com/questions/11465204
复制相似问题