2012-07-13 59 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/

,並獲得關於你提到的「指針」問題的關注清晰在這個問題中,閱讀「如何嵌套結構初始化?」一節。在上面的指南。

相關問題