1

I have two different application. I have to send information from one app to another. In one application there is encoding in class object and in another application it is decoded in structure object with same data types.

Is it correct implementation to copy class object to structure who have same data types? or should i have to change in one of encoding/decoding part?

I tried it, it seems correct memcpy but i don't understand that it is correct or not..

For example...

#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 Answers1

5

You have two problems here.

  1. How to serialize your object,
  2. How to transfer it to another address space.

Serialization with memcpy is possible only if the object contains POD members AND you know low level architecture details like alignment, endianess etc (Trivially Copiable). For less trouble, you can try serializing to XML.

To transfer to a receiver it depends on where the receiver is. If, for example, it's a different address space, then you can use Sockets, or (in Windows) File Mapping. If it's a DLL in same address space, you can simply share a pointer to the serialized data.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78