Search code examples
c++pointerscastingreverse-engineeringfunction-calls

C++ taking a pointer and turning it into a callable function


I am currently reverse engineering a program to learn how it works and have just completed disassembling a function that the program calls. The starting address of the function is stored in a pointer, and it takes 4 arguments. My goal is to now cast the pointer as a callable function.

I have seen this done before a year or two ago, but no longer have access to the example code that was used. Essentially, I want to take a pointer that points to the start of a function and convert it into this:

void AddValueToMain(void* basePtr, unsigned int value, __int64 compareValue, __int64 ONE_BILLION);

How can I cast this pointer so that I can call the function as if it were written in C++?


Solution

  • You can reinterpret_cast to a function pointer. Assuming that m_ptr holds the pointer to the function:

    auto AddValueToMain = reinterpret_cast<void(*)(void*,unsigned int,__int64,__int64)>(m_ptr);
    

    Now you can call AddValueToMain just like a normal function:

    AddValueToMain(ptr, 42, 2, 4);