通过 c++ 中的 udp 套接字将派生类对象从一个进程发送到另一个进程

Send an derived class object from one process to another via udp socket in c++

本文关键字:进程 一个 另一个 udp 中的 c++ 套接字 对象 派生 通过      更新时间:2023-10-16

假设我们有一个类,叫做 Derived 从类继承的,叫做 Base。 这两个类仅包含连续内存区域中的数据。是否可以通过网络发送派生类的对象,而无需实现任何用于序列化和反序列化对象成员的特殊函数?vtable会发生什么?vtable 保留派生函数的真实地址还是只是偏移量?

看看下面的代码段

#include "pch.h"
#include <iostream>
#include "Base.h"
class Derived : public Base
{
public:
char dummy[100];
int c;
~Derived()
{
}
void serialize(RtpComMsg_t msg)
{
msg.length = sizeof(*this);
msg.data = reinterpret_cast<unsigned char *>(this);
std::cout << "1.msg length" << msg.length << std::endl;
}
};
void Base::serialize(RtpComMsg_t msg)
{
msg.length = sizeof(*this);
msg.data = reinterpret_cast<unsigned char *>(this);
std::cout << "msg length" << msg.length << std::endl;
}

//receive from network
void deserialize(void * data)
{
Derived *d = reinterpret_cast<Derived *>(data);
}

int main()
{
Base *b = new Derived()  ;
b->a = 5;
memcpy(((Derived*)b), "0xABCDEF", sizeof("0xABCDEF"));
((Derived*)b)->c = 10;
RtpComMsg_t msg{};
b->serialize(msg);
unsigned char temp[sizeof(Derived)];
memcpy(temp, b, sizeof(Derived));
//send temp to network
return 0;
}

一般来说,切勿通过网络发送指针。不同的操作系统、不同的硬件、不同的编译器、不同的编译器版本,甚至不同的程序构建 - 都可能破坏代码。我什至没有提到收到的数据出错的可能性。

最好的建议:制定简单的约定 - 它是什么样的数据以及它适用于谁。在基本程序中,您甚至可以简化它(直到您的TCP套接字由于未知原因无法接收发送的数据,发生在我身上(。