一个struct在C一个char *的序列化/反序列化 [英] Serialization/Deserialization of a struct to a char* in C

查看:629
本文介绍了一个struct在C一个char *的序列化/反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构

struct Packet {
    int senderId;
    int sequenceNumber;
    char data[MaxDataSize];

    char* Serialize() {
        char *message = new char[MaxMailSize];
        message[0] = senderId;
        message[1] = sequenceNumber;
        for (unsigned i=0;i<MaxDataSize;i++)
            message[i+2] = data[i];
        return message;
    }

    void Deserialize(char *message) {
        senderId = message[0];
        sequenceNumber = message[1];
        for (unsigned i=0;i<MaxDataSize;i++)
            data[i] = message[i+2];
    }

};

我需要这在另一端转换为一个char *,最大长度MaxMailSize> MaxDataSize发送通过网络,然后反序列化

I need to convert this to a char* , maximum length MaxMailSize > MaxDataSize for sending over network and then deserialize it at the other end

我不能使用第三方物流或任何其他库。

有什么办法让这个更好的,我不是这一点,舒服,或者这是我们能做的最好的。

Is there any way to make this better I am not that comfortable with this, or is this the best we can do.

推荐答案

,因为这是通过网络发送,我强烈建议你在发送前对这些数据转换成网络字节顺序转换,并返回到主机字节顺序接收时。这是因为,字节顺序是不一样的随处可见,一旦你的字节不是以正确的顺序,它可能会变得非常难以扭转他们(取决于在接收侧使用的程序设计语言)。字节排序功能与插座一起定义,并命名为 htons() htonl() ntohs和() ntohl()。 (这些名字:h表示主机或您的计算机中,N表示网络,S表示短或16bit值,L的意思是'长'或32位值)

since this is to be sent over a network, i strongly advise you to convert those data into network byte order before transmitting, and back into host byte order when receiving. this is because the byte ordering is not the same everywhere, and once your bytes are not in the right order, it may become very difficult to reverse them (depending on the programming language used on the receiving side). byte ordering functions are defined along with sockets, and are named htons(), htonl(), ntohs() and ntohl(). (in those name: h means 'host' or your computer, n means 'network', s means 'short' or 16bit value, l means 'long' or 32 bit value).

那么你是你自己用系列化,C和C ++都没有执行它自动方式。一些软件可以生成code来为你做它,就像ASN.1实施ASN1C,但它们很难使用,因为它们涉及的不仅仅是在网络上复制数据等等。

then you are on your own with serialization, C and C++ have no automatic way to perform it. some softwares can generate code to do it for you, like the ASN.1 implementation asn1c, but they are difficult to use because they involve much more than just copying data over the network.

这篇关于一个struct在C一个char *的序列化/反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆