Soo
Soo

Reputation: 1017

Copying the address of an object into a buffer and retrieving it

I would like to copy the address of an object to a buffer and typecast it back at some other point. I am unable to do it. A sample code is given below.

 #include <iostream>
#include <cstring>

class MyClass
{

public:
    MyClass(const int & i)
    {
        id = i;
    }


    ~MyClass()
    {

    }


    void print() const
    {
        std::cout<<" My id: "<<id<<std::endl;           
    }

private:
    int id; 
};



int main()
{


MyClass *myClass = new MyClass(10);
std::cout<<"myClass: "<<myClass<<std::endl; 
myClass->print();

// Need to copy the address to a buffer and retrieve it later
char tmp[128];
//  std::vector tmp(sizeof(myClass); // preferably, we may use this instead of the previous line, and use std::copy instead of memcpy

memcpy(tmp, myClass, sizeof(myClass));


// retreiving the pointer   
MyClass* myClassPtr = (MyClass*) tmp;
std::cout<<"myClassPtr: "<<myClassPtr<<std::endl;
myClassPtr->print();

return 0;
}

In fact, the pointers gives different values, which is the source of the problem. What am I doing wrong here?

Upvotes: 0

Views: 44

Answers (1)

Matteo Italia
Matteo Italia

Reputation: 126867

You are copying (a pointer-sized part of) the object itself, not the pointer. You should do:

memcpy(tmp, &myClass, sizeof(myClass));

and then back:

MyClass *ptr;
memcpy(&ptr, tmp, sizeof(ptr));

Upvotes: 1

Related Questions