Search code examples
c++dllreverse-engineering

Call a member function with offset address from Dll


I have non-exported member function in a dll.
I'm trying to call this function with base + offset address I extracted before.
I have a problem to do the actual calling from the class instance.

I I was able to get the base address of the module and the offset of the function from the dll.
I got an error calling the function because it not a member of my class.

HMODULE hDll = GetModuleHandleA("myModule.dll");

void *(funcPtr)() = (void(*)())((char *)&hDll + 0x101E07); //this is the non exported function address
myClassInstance->funcPtr();

I'm getting an error:

'funcPtr' is not a member of 'MyClass'

How do I make the call of funcPtr from myClassInstance?


Solution

  • This is not an simple thing to do. First, you need to declare your pointer as a member function pointer:

    void (MYCLASS::*funcPtr)();
    

    And you'd call it via

    (myClassInstance->*funcPtr)();
    

    Then you need some way to store a value in there. You can't cast a char * (or void *) pointer to a member function pointer. You'll have to use some form of type punning.

    The typical way is to use memcpy:

    void *addr = (char *)&hDll + 0x101E07;
    memcpy(&funcPtr, &addr, sizeof(void *));
    

    Another possibility, since getting the address of the member function from the DLL is already over the line for Undefined Behavior, might be using a union:

    union MemFuncPtr {
        void *addr;
        void (MYCLASS::*memfun)();
        // Can be expanded to include other member function pointer types if necessary
    };
    

    Then you can just

    MemFuncPtr mfp;
    mfp.addr = (char *)&hDll + 0x101E07;
    funcPtr = mfp.memfun;
    

    Or you can try the very ugly reference cast on the left side of the assignment.

    There are additional possible complications if the function you're getting the address of is virtual and myClassInstance points to a derived class, or if multiple inheritance is involved.

    Proceed at your own risk.