P
P
Pavel K2018-02-01 02:02:51
Qt
Pavel K, 2018-02-01 02:02:51

How to get the address of the heir?

Greetings!
There is a class, MyClass, inherited from the abstract class IInterface

MyClass * myClass = new MyClass(0);
IInterface * interface = myClass;

I only have the interface address at my disposal, nothing else! those. Yes, the MyClass header, I cannot change the IInterface or MyClass code.
How to get the address of myClass from it?
If I c do:
qDebug()<<"MyClass"<<myClass;
qDebug()<<"Interface"<<interface;

then of course the addresses are different ...
you need to somehow get the address of myClass through the interface.
You can move the pointer, for example, by 2 and get the desired address, but this is a crutch.
PS Yes, it's really necessary, but I'm sure.
PPS code for example. In reality, there is only the IInterface header and the interface variable - a pointer to it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2018-02-01
@PavelK

That's exactly what to do. Because you are required to set up the “Public Morozov” template in very difficult conditions (there is not even a title). So you have to repeat what the compiler and linker usually do.
The arrangement of virtual method tables and dynamic_cast in your compiler can help. For example, on MinGW I got this.

#include <iostream>


class A {
public:
    int a;
    virtual void doA() {}
    virtual ~A() = default;
};

// class B, C, D, E  аналогично {

class DE : public D, public E { int de; };
class AB : public A, public B { int ab; };
class CDE : public C, public DE { int cde; };

class All : public AB, public CDE {};


struct Vtable {
    uint32_t d[1];
};

union PObject {
    void* asVoid;
    Vtable** asVtable;
    char* asRaw;
};

int main()
{
    All all;
    All* pAll = &all;
    E* pThis = &all;
    std::cout << pAll << " " << pThis << std::endl;

    PObject pX;
    pX.asVoid = pThis;
    while (true) {
        uint32_t offset = -(*pX.asVtable)->d[-2];
        std::cout << "Got offset " << offset << std::endl;
        if (offset == 0)
            break;
        pX.asRaw -= offset;
        std::cout << "Got pointer " << pX.asVoid << std::endl;
    }

    return 0;
}

An intermediate child (DE or CDE) could not be reached.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question