Windows: Get function address in C++ Windows: Get function address in C++ windows windows

Windows: Get function address in C++


Visual Studio "lies" to you here. When you print either funcptr or gio you see the actual address, that is the address you jump to when writing

gio() // or funcptr()

With Incremental Linking enabled this value is different from what Visual Studio tells you when you hover over gio because of thunking, see /INCREMENTAL.

May contain jump thunks to handle relocation of functions to new addresses.

To figure out the address of your code you can either disable Incremental Linking or
use the DIA SDK:

// initialize DIA SDK, etc.void (*fp)() = &foo;printf("foo(): %p\n\n", foo);HMODULE hModule = GetModuleHandle(NULL);DWORD rva = (DWORD)((size_t)fp - (size_t)hModule);IDiaSymbol *pDiaSymbol;hr = pDiaSession->findSymbolByRVA(rva, SymTagPublicSymbol, &pDiaSymbol);if(FAILED(hr) || !pDiaSymbol)    return hr;ULONGLONG targetVA;hr = pDiaSymbol->get_targetVirtualAddress(&targetVA);pDiaSymbol->Release();if(FAILED(hr))    return hr;if(hr == S_OK)    printf("foo is a thunk, actual address: %p\n\n", (LPVOID)((size_t)hModule + targetVA));

But there might be a simpler way that I'm not aware of.