I have a container class B and it has certain number of items of A. I want to serialize it for sending either over wire or save it to disk.
class A {
public:
bool b;
long c;
};
struct B {
public:
int na;
bool bb;
A** a;
};
void send(unsigned char* ptr, int sizeb) {
int i = sizeof(B);
B* b = new B();
b->a = (A**)malloc((int)*ptr * sizeof(A*));
while (i < sizeb) {
memcpy(b->a[i], ptr + i, sizeof(A));
i += sizeof(A);
}
}
The first member of B is the number of contained A items. In this case it's three.
int main()
{
B* b = new B();
b->na = 3;
b->bb = true;
b->a = (A**)malloc(b->na *sizeof(A*));
for (int i = 0; i < b->na; i++) {
b->a[i] = new A();
b->a[i]->b = true;
b->a[i]->c = (i+1) * 100;
}
int sizeb = sizeof(B) + b->na * sizeof(A);
unsigned char* ptr = (unsigned char*)malloc(sizeb);
memcpy(ptr, (unsigned char*)&b, sizeof(B));
for (int i = 0; i < b->na; i++)
memcpy(ptr+i*sizeof(A), (unsigned char*)&b->a[i], sizeof(A));
send(ptr, sizeb);
return 0;
}
First I allocate enough contigous space for storing B and the three A's. In the send method I don't get back the na value. What's wrong?
You're not copying what you think you're copying:
memcpy(ptr, (unsigned char*)&b, sizeof(B));
for (int i = 0; i < b->na; i++)
memcpy(ptr+i*sizeof(A), (unsigned char*)&b->a[i], sizeof(A));
b is already a pointer to B, so when you take its address you now have a B **. The same happens with &b->a[i] which evaluated to a A **. You also overwrite the instance of B with the first instance of A.
You already have pointers to the data you want to copy, so pass those directly to memcpy, and add sizeof(b) to ptr when adding the instances of A.
memcpy(ptr, b, sizeof(B));
for (int i = 0; i < b->na; i++)
memcpy(ptr+sizeof(B)+i*sizeof(A), b->a[i], sizeof(A));
Then in your send function, you're not deserializing the instance of B. You need to do that as well.
B* b = new B();
memcpy(b, ptr, sizeof(b);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With