Calling a function from another process

2

I apologize in advance for my English :D

How can I call a function from a process, knowing the pointer to it?

I tried this:

Process.cpp:

DWORD pid;
HWND hwnd;
HANDLE phandle;

void Attach() {
    hwnd = FindWindow(NULL, L"GTA:SA:MP");
    if (!hwnd) {
        cout << "Process is not found" << endl;
        system("pause");
    }
    else if (hwnd) {
        cout << "Process was successfully loaded" << endl;
        GetWindowThreadProcessId(hwnd, &pid);
        phandle = OpenProcess(PROCESS_VM_READ, 0, pid);
    }
    else
    {
        cout << "Error 0x01" << endl;
        system("pause");
    }
}

void GameText(const char* szText, int iTime, signed int iStyle)
{
    typedef void(__stdcall* GameText_t)(const char*, int, signed int);
    GameText_t pGameText = (GameText_t)((char*)phandle + 0x69F2B0);
    return pGameText(szText, iTime, iStyle);
}

main.cpp:

int main()
{

    std::cout << "Hello World!\n"; 

    Attach();

    GameText("~r~Test!", 1000, 5);

}

And I get the following exception:

An exception was thrown at the address 0x006EF7B6 in wh_mta.exe: 0xC0000005: access violation during execution at 0x006EF7B6.

Why is this happening? How can I call a function by its pointer through HANDLE?

P.S

Reading an integer through HANDLE works great.

int Read_Int(int address) {
    int value;

    ReadProcessMemory(phandle, (void*)address, &value, sizeof(value), 0);

    return value;
}
c++
windows
asked on Stack Overflow Oct 7, 2018 by NoName_as_Null • edited Oct 7, 2018 by melpomene

2 Answers

5

Maybe 30 years ago that would have worked :D :D :D

Processes can't access each other's memory… Every process has their own image of the memory, so address 0xWHATEVER in a process does not contain the same data as 0xWHATEVER in another process!

You need to make a library or use some inter process communication (IPC).

answered on Stack Overflow Oct 7, 2018 by LtWorf
0

What you are doing is adding the pointer to the HANDLE of the process. You need the address of the process in it's virtual address space. To do so, use EnumProcessModules andGetModuleFileNameEx to find the filename of the module with the function you want. (Could be an EXE or a DLL.) EnumProcessModules returns an array of HMODULES which are just addresses of module in the specified process's virtual address space. So loop through the array, then cast the HMODULE that you need to a PBYTE. Then, add the function pointer to it, then try to execute.

Also, according your code, you are going to execute the function in YOUR program. That's fine, just make sure that if it needs to run in the target program, you'll need to use CreateRemoteThread to run it there.

answered on Stack Overflow Oct 14, 2018 by Arush Agarampur

User contributions licensed under CC BY-SA 3.0