2012-07-13 129 views

回答

0

使用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指针的生存期。

1

你可以用节俭这一点。 定义将看起来像

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/

,并获得关于你提到的“指针”问题的关注清晰在这个问题中,阅读“如何嵌套结构初始化?”一节。在上面的指南。