Home > database >  Can I cast a memory area with a class type?
Can I cast a memory area with a class type?

Time:01-01

class RW {
    int a;
public:
    int read() const {
        return this->a;
    }
    void write(int _a) {
        this->a = _a;
    }
};

#define PHYSICAL_ADDRESS (0x60000000)
#define SIZEOF_PHY_ADDR  (sizeof(RW))
// assume physical memory area is already assigned for the sizeof(RW)

void main()
{
    int val;
    void *phy_ptr = PHYSICAL_ADDRESS;
    RW *rw_ptr = (RW *)phy_ptr;

    rw_ptr->write(1);
    val = rw_ptr->read();
}

Please assume that the code above is pseudo code. I have a shared physical memory area which is read/writable. And I want to cast the pointer of that area to read and write. Can I do this and is it acceptable?

I have checked it works fine but I am not sure if it's right cpp manner.

I appreciate any response and discussion! Thanks in advance!

CodePudding user response:

You don't need to cast: you may just create the object at that address with placement new operator.

void main()
{
    int val;
    void *phy_ptr = PHYSICAL_ADDRESS;
    //RW *rw_ptr = (RW *)phy_ptr;
    RW *rw_ptr = new(phy_ptr) RW;

    rw_ptr->write(1);
    val = rw_ptr->read();

    rw_ptr->~RW();
}
  •  Tags:  
  • c
  • Related