从类对象到结构变量的 memcpy

memcpy from class object to structure variable

本文关键字:变量 memcpy 结构 对象      更新时间:2023-10-16

我有两个不同的应用程序。我必须将信息从一个应用程序发送到另一个应用程序。在一个应用程序中,类对象中有编码,而在另一个应用程序中,它在具有相同数据类型的结构对象中进行解码。

将类对象复制到具有相同数据类型的结构是正确的实现吗? 还是我应该更改编码/解码部分之一?

我试过了,它似乎是正确的memcpy,但我不明白它是否正确。

例如。。。

#include <iostream>
#include <cstring>
class capn{
    public:
    unsigned short int apn[8];
    unsigned short int a;
};
class creq{
    public:
    capn a1;
    capn a2;
    unsigned short int t;
    capn a3;
};
class cy{
    public:
    capn a1;
    capn a2;
    unsigned short int aaa[34];
    capn a3;
    unsigned short int bbb[12];
};
class cx{
    public:
    cx(){
        a=0;
        b=0;
        c=0;
        memset(d,0,8);
    }
    unsigned int a;
    unsigned int b;
    unsigned int c;
    union {
        creq requ;
        cy pasd;
    };
    unsigned short int d[8];
};

struct apn{
    unsigned short int apn[8];
    unsigned short int a;
};
struct req{
    struct apn a1;
    struct apn a2;
    unsigned short int t;
    struct apn a3;
};
struct y{
    struct apn a1;
    struct apn a2;
    unsigned short int aaa[34];
    struct apn a3;
    unsigned short int bbb[12];
};
struct x{
    unsigned int a;
    unsigned int b;
    unsigned int c;
    union {
        struct req requ;
        struct y pasd;
    };
    unsigned short int d[8];
};
int main()
{
    struct x ox;
    ox.a=1;
    ox.b=2;
    ox.c=3;
    ox.d[0]=4;
    ox.requ.a1.a=5;
    ox.requ.t=6;
    cx obj;
    std::cout<<sizeof(ox)<<std::endl;
    std::cout<<sizeof(obj)<<std::endl;
    memcpy(&obj,&ox,sizeof(ox));
    std::cout<<obj.a<<" " <<obj.b<< " " <<obj.c<< " "<<obj.d[0]<< " " <<obj.requ.a1.a<<" "<<obj.requ.t<<std::endl;
    return 0;
}

你这里有两个问题。

  1. 如何序列化你的对象,
  2. 如何将其传输到另一个地址空间。

仅当对象包含 POD 成员并且您知道低级架构细节(如对齐、字节序等(时,才可以使用 memcpy 进行序列化。为了减少麻烦,您可以尝试序列化为 XML。

要传输到接收器,这取决于接收器的位置。例如,如果它是一个不同的地址空间,则可以使用套接字或(在 Windows 中(文件映射。如果它是同一地址空间中的 DLL,则只需共享指向序列化数据的指针即可。