Search code examples
c++vtable

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


Let's say that we have a class, is called Derived that inherits from a class is called Base. The two classes contains only data that are in continuous memory regions. Is it possible to send an object of the derived class over network without implement any special function for serialize and de-serialize the member of the object? What will be happen with the vtable? The vtable keeps real address of the derived functions or just offset?

Have a look in the following piece of code

#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;
}

Solution

  • Generally speaking, you should never send a pointer via networking. Different OS, different hardware, different compiler, different compiler version, or even different program build - might potentially break the code. I don't even mention the possibility of received data having errors.

    Best advise: make simple conventions - what kind of data it is and who is it for. In basic programs you can even simplify it (till your TCP socket fails to receive sent data for unknown reason, happened to me).