C++ read from class by its pointer and offset

1.3k Views Asked by At

Ida pro generates this line in pseudo-code, and I have working class pointer and reverse engineered class, but I don't want to read something directly from class file.

Example in IDA Pro:

*(_DWORD *)(v3 + 9649) = 1;

// Alignment: 1
class CVehicle
{
    DWORD modelid; // 0
    float pos[3]; // 4
    WORD player; // 16
}

CVehicle *pVehicle;

I know, if I want to get player, then I need to do that:

pVehicle->player

But what if I want to get player by offset? Because sometime I need to read by offset because I didn't reverse engineered the complete class. Example

*(WORD*)(pVehicle + 16) // That should work, should return player, but will crash. Why?
1

There are 1 best solutions below

0
On

Assuming I understand what you're saying in your posting, this is how I'd do it:

Header:

#pragma pack(push, 1)
class CPlayer
{
public:
    unsigned char Unknown00[9649];
    char Unknown9649;
};

class CVehicle
{
public:
    DWORD modelid; // 0
    float pos[3]; // 4
    CPlayer *pPlayer; // 16
};
#pragma pack(pop)

Code:

char SomethingIWant;
CVehicle *pVehicle; // set previously
CPlayer *pPlayer = nullptr;

if (pVehicle)
   pPlayer = pVehicle->pPlayer;
if (pPlayer)
   SomethingIWant = pPlayer->Unknown9649;

Then, you can just fill in the classes as you go and discover more information.

(Disclaimer: The code above assumes that pVehicle->pPlayer is either nullptr or valid. Otherwise, more code would be needed to properly verify that pPlayer is valid.)