从类对象到结构变量的 memcpy
memcpy from class object to structure variable
我有两个不同的应用程序。我必须将信息从一个应用程序发送到另一个应用程序。在一个应用程序中,类对象中有编码,而在另一个应用程序中,它在具有相同数据类型的结构对象中进行解码。
将类对象复制到具有相同数据类型的结构是正确的实现吗? 还是我应该更改编码/解码部分之一?
我试过了,它似乎是正确的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;
}
你这里有两个问题。
- 如何序列化你的对象,
- 如何将其传输到另一个地址空间。
仅当对象包含 POD 成员并且您知道低级架构细节(如对齐、字节序等(时,才可以使用 memcpy 进行序列化。为了减少麻烦,您可以尝试序列化为 XML。
要传输到接收器,这取决于接收器的位置。例如,如果它是一个不同的地址空间,则可以使用套接字或(在 Windows 中(文件映射。如果它是同一地址空间中的 DLL,则只需共享指向序列化数据的指针即可。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 为什么我可以使用 memcpy 将一个对象变量复制到另一个对象变量
- memcpy() 在一个类中被调用以复制到另一个类变量中后会引发异常
- 从类对象到结构变量的 memcpy
- memcpy(),非初始化的局部变量
- memcpy局部静态变量时出现分段错误
- 如何获得指向memcpy成员变量的指针