15

假设我有一个结构,我想通过网络将其成员值发送到使用 winsock 2 的另一个系统。我使用的是 C++ 语言。如何将其转换为 char * 请记住,结构必须在发送之前进行序列化,以及如何将 char * 反序列化为另一端的结构?我发现提升序列化是对类似问题的建议,但任何人都可以用一个小代码片段来说明序列化和反序列化吗?

这个问题可能看起来很基本,但相关帖子的其他答案并没有太大帮助。

4

5 回答 5

22

以下示例显示了序列struct化为char数组并对其进行反序列化的最简单方法。

#include <iostream>
#include <cstring>

#define BUFSIZE 512
#define PACKETSIZE sizeof(MSG)

using namespace std;

typedef struct MSG
{
    int type;
    int priority;
    int sender;
    char message[BUFSIZE];
}MSG;

void serialize(MSG* msgPacket, char *data);
void deserialize(char *data, MSG* msgPacket);
void printMsg(MSG* msgPacket);

int main()
{
    MSG* newMsg = new MSG;
    newMsg->type = 1;
    newMsg->priority = 9;
    newMsg->sender = 2;
    strcpy(newMsg->message, "hello from server\0");
    printMsg(newMsg);

    char data[PACKETSIZE];

    serialize(newMsg, data);

    MSG* temp = new MSG;
    deserialize(data, temp);
    printMsg(temp);

    return 0;
}

void serialize(MSG* msgPacket, char *data)
{
    int *q = (int*)data;    
    *q = msgPacket->type;       q++;    
    *q = msgPacket->priority;   q++;    
    *q = msgPacket->sender;     q++;

    char *p = (char*)q;
    int i = 0;
    while (i < BUFSIZE)
    {
        *p = msgPacket->message[i];
        p++;
        i++;
    }
}

void deserialize(char *data, MSG* msgPacket)
{
    int *q = (int*)data;    
    msgPacket->type = *q;       q++;    
    msgPacket->priority = *q;   q++;    
    msgPacket->sender = *q;     q++;

    char *p = (char*)q;
    int i = 0;
    while (i < BUFSIZE)
    {
        msgPacket->message[i] = *p;
        p++;
        i++;
    }
}

void printMsg(MSG* msgPacket)
{
    cout << msgPacket->type << endl;
    cout << msgPacket->priority << endl;
    cout << msgPacket->sender << endl;
    cout << msgPacket->message << endl;
}
于 2013-12-30T10:50:15.833 回答
6

你可以做

struct MyStruct {

    int data;
    char* someNullTerminatedName; // Assuming not larger than 1023 chars

    std::ostream& serialize(std::ostream& os) const {
        char null = '\0';
        os.write((char*)&data, sizeof(data));
        os.write(someNullTerminatedName, strlen(someNullTerminatedName));
        os.write(&null, 1);
        return os;
    }
    std::istream& deserialize(std::istream& is) {
        char buffer[1024];
        int i = 0;
        is.read((char*)&data, sizeof(data));
        do { buffer[i] = is.get(); ++i; } while(buffer[i] != '\0');
        if (someNullTerminatedName != NULL) free(someNullTerminatedName);
        someNullTerminatedName = (char*)malloc(i);
        for (i = 0; buffer[i] != '\0'; ++i) {
            someNullTerminatedName[i] = buffer[i];
        }
        return is;
    }
};

由你来处理字节顺序和ints 大小的差异等等。

例子:

MyStruct foo, bar;
std::stringstream stream;
foo.serialize(stream);
// ... Now stream.str().c_str() contains a char* buffer representation of foo.
// For example it might contain [ 1f 3a 4d 10 h e l l o w o r l d \0 ]
bar.deserialize(stream);
// ... Now bar is a copy, via a serial stream of data, of foo.

如果您有一个通过 C++ iostreams 公开其接口的套接字库,那么您甚至不需要字符串流。

于 2013-05-14T13:22:23.890 回答
5

您还可以查看 Google 的Protocol Buffers,它是一个独立于平台/语言的库,用于在主机之间发送数据。

但是,范式转向首先编写协议,然后将数据结构放入其中。这样做的好处是它迫使您的软件架构很好地适应简单的数据类型。

于 2013-05-14T13:28:21.763 回答
3

如果你的结构是POD你可以使用memcpy

::memcpy(data, &your_struct, sizeof(YourStruct)));

在接待处反之亦然:

::memcpy(&your_struct, data, sizeof(YourStruct)));

data一个在哪里char*。不要忘记你必须分配它,确保它足够大并在最后删除它。

于 2013-05-14T12:59:24.447 回答
1

好的,我将从boost 网站举个例子,因为我不明白你不能从中理解什么。
我添加了一些评论和更改,您可以如何通过网络传输。网络代码本身不在此处。为此,您可以查看boost::asio

int main() {
    // create and open a character archive for output
    // we simply use std::strinstream here
    std::stringstream ofs;

    // create class instance
    const gps_position g(35, 59, 24.567f);

    // save data to archive
    {
        boost::archive::text_oarchive oa(ofs);
        // write class instance to archive
        oa << g;
        // archive and stream closed when destructors are called
    }

    // now we have const char* ofs.str().c_str()
    // transfer those bytes via network
    // read them on the other machine

    gps_position newg;
    {
        // create and open an archive for input
        std::stringstream ifs(the_string_we_read_from_the_network);
        boost::archive::text_iarchive ia(ifs);
        // read class state from archive
        ia >> newg;
        // archive and stream closed when destructors are called
    }
    return 0;
}
于 2013-05-14T13:13:04.120 回答