//功能:得到某个API函数代码地址
//参数://hModule: 导入模块的句柄(如user32.dll模块的句柄,GetModuleHandle("user32.dll"))
//pProcName: 函数名或序号
const FARPROC GetExportFunctionFARPROC(HMODULE hModule, LPCSTR pProcName)
{
PIMAGE_EXPORT_DIRECTORY pExport = (PIMAGE_EXPORT_DIRECTORY)
GetDirectory(IMAGE_DIRECTORY_ENTRY_EXPORT);
if ( pExport==NULL )
return NULL;
unsigned ord = 0;
if ( (unsigned) pProcName < 0xFFFF ) // ordinal ?
ord = (unsigned) pProcName;
else
{
const DWORD * pNames = (const DWORD *) RVA2Ptr(pExport->AddressOfNames);
const WORD * pOrds = (const WORD *) RVA2Ptr(pExport->AddressOfNameOrdinals);
// find the entry with the function name
for (unsigned i=0; i<pExport->AddressOfNames; i++)
if ( stricmp(pProcName, RVA2Ptr(pNames[i]))==0 )
{
// get the corresponding ordinal
ord = pExport->Base + pOrds[i];
break;
}
}
if ( (ord<pExport->Base) || (ord>pExport->NumberOfFunctions) )
return NULL;
// use ordinal to get the address where export RVA is stored
const char * pModule = (const char *) hModule;
DWORD * pRVA = (DWORD *) (pModule + pExport->AddressOfFunctions) +
ord - pExport->Base;
// read original function address
DWORD rslt = * pRVA;
return (FARPROC) (pModule + rslt);
}