2013-07-18 4 views
0

의 직렬화는 I는 구조를 갖는다.직렬화 및 C의 이차원 float 배열 ++

네트워크를 통해 구조와 data을 전송해야합니다. 올바르게 serialize/deserialize하는 방법?

Desc desc; 
desc.rows = 32; 
desc.cols = 1024; 
float data[rows][cols]; 
// setting values on array 
char buffer[sizeof(Desc)+sizeof(float)*desc.rows*desc.probes]; 
memcpy(&buffer[0], &desc, sizeof(Desc)); // copying struct into the buffer 
memcpy(&buffer[0]+sizeof(Desc), &data, sizeof(float)*rows*probes); // copying data into the buffer 

을하지만이 올바른 접근 방식의 경우 잘 모르겠어요 :

이것은 내가 지금 할 것입니다.

누군가이 방법에 대한 힌트를 줄 수 있습니까?

+0

직렬화가 다릅니다. 유선을 통해 보낼 수있는 형식을 만들어야합니다.이 형식은 일반적으로 문자열로 변환하여 수행됩니다. char 배열에 대한 바이너리 복사를해서는 안된다. http://en.wikipedia.org/wiki/Serialization을 참조하십시오. – hetepeperfan

답변

0

NOT 이진 직렬화를 사용하는 것이 좋습니다. 예를 들어 일반 텍스트 (표준 : 이제 stringstream), JSON, XML 등

С ++ 예 :

int width = 10; 
int height = 20; 
float array[height][width]; 
std::stringstream stream; 
stream << width << " " << height << " "; 
for (int i = 0; i < height; ++i) 
{ 
    for (int j = 0; j < width; ++j) 
    { 
    stream << array[i][j] << " "; 
    } 
} 

std::string data = stream.str(); 
// next use the data.data() and data.length() 
1

당신이 C++로 유지하고 효율적으로하려면 내가 Boost Serialization를 사용합니다 - 그렇지 않으면 JSON을 네 친구일지도 몰라. demo을 구조체를 serialize하기 위해 파일에 적용 시켰지만 기본적으로 스트림간에 쓰거나 읽습니다.

#include <fstream> 
#include <boost/archive/text_oarchive.hpp> 
#include <boost/archive/text_iarchive.hpp> 

struct Desc { 
    int rows; 
    int cols; 

    private: 

    friend class boost::serialization::access; 

    template<class Archive> 
    void serialize(Archive & ar, const unsigned int version) 
    { 
     ar & rows; 
     ar & cols; 
    } 

    public: 
    Desc() 
    { 
     rows=0; 
     cols=0; 
    }; 

}; 

int main() { 

    std::ofstream ofs("filename"); 

    // prepare dummy struct 
    Desc data; 
    data.rows=11; 
    data.cols=22; 

    // save struct to file 
    { 
     boost::archive::text_oarchive out_arch(ofs); 
     out_arch << data; 
     // archive and stream closed when destructors are called 
    } 

    //...load struct from file 
    Desc data2; 
    { 
     std::ifstream ifs("filename"); 
     boost::archive::text_iarchive in_arch(ifs); 
     in_arch >> data2; 
     // archive and stream closed when destructors are called 
    } 
    return 0; 
} 

참고 :이 예제가 작동하는지 확인하지 않았습니다.

* Jost