我正在尝试在Windows运行时从dll加载函数。我尝试基于此程序来打印自己的模块程序:https : //docs.microsoft.com/en-us/windows/win32/psapi/enumerating-all-modules-for-a-process。
我需要两个函数来执行我想要的操作:EnumProcessModules和GetModuleFileNameExA。我设法在运行时从psapi.dll中获取了这两个文件,但是GetModuleFileNameExA不能正常运行,我也不能说为什么
这是我写的功能脚本:
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <psapi.h>
typedef DWORD (__cdecl *EnumModules)(HANDLE hprocess, HMODULE *moduleHandles, DWORD cb, LPDWORD lpcNeeded);
typedef DWORD (__cdecl *GetModuleName)(HANDLE hprocess, HMODULE hmodule, LPSTR name, DWORD size);
void ErrorMessage(const char *message){
fprintf(stderr, message);
exit(EXIT_FAILURE);
}
int PrintModules( HANDLE pHandle )
{
HMODULE hMods[1024];
DWORD cbNeeded;
unsigned int i;
if (NULL == pHandle)
return EXIT_FAILURE;
// Loads the lib
HMODULE psapiLib = LoadLibrary("C:\\Windows\\SysWOW64\\psapi.dll");
if(! psapiLib) ErrorMessage("Error loading psapi.dll\n");
// Get the functions we need from the lib
EnumModules getModules = (EnumModules)GetProcAddress(psapiLib, "EnumProcessModules");
GetModuleName getModuleName = (GetModuleName)GetProcAddress(psapiLib, "GetModuleFileNameExA");
if(!getModules) ErrorMessage("Error finding EnumProcessModules from psapi.dll\n");
if(!getModuleName) ErrorMessage("Error finding GetModuleFileNameExA from psapi.dll\n");
// Get a list of all the modules in this process.
if( getModules(pHandle, hMods, sizeof(hMods), &cbNeeded))
{
for ( i = 0; i < (cbNeeded / sizeof(HMODULE)); i++ )
{
LPSTR szModName;
szModName = malloc(1024 * sizeof(LPSTR));
// Get the full path to the module's file.
// change GetModuleFileNameExA with getModuleName to see the error
if ( GetModuleFileNameExA( pHandle, hMods[i], szModName, 1024 * sizeof(char))){
// Print the module name and handle value.
printf(("\t%s (0x%08X)\n"), szModName, hMods[i] );
}
free(szModName);
}
}
return 0;
}
int main( void )
{
HANDLE myHandle = GetCurrentProcess();
PrintModules(myHandle);
CloseHandle(myHandle);
return 0;
}
如果我改变这部分
if ( GetModuleFileNameExA( pHandle, hMods[i], szModName, 1024 * sizeof(char))){
// Print the module name and handle value.
printf(("\t%s (0x%08X)\n"), szModName, hMods[i] );
}
对此
if ( getModuleName( pHandle, hMods[i], szModName, 1024 * sizeof(char))){
// Print the module name and handle value.
printf(("\t%s (0x%08X)\n"), szModName, hMods[i] );
}
因此它会改用我的函数,而无需在加载时链接psapi.dll,这是行不通的。它将出现段错误或不打印任何内容。我试图改变我如何呈现缓冲区,尝试使用widechar或Tchar,但似乎没有任何效果。
有趣的是,函数之一getModules(指向EnumProcessModules)工作得很好!我只是不明白发生了什么。
您应该更改此行代码
typedef DWORD (__cdecl *EnumModules)(HANDLE hprocess, HMODULE *moduleHandles, DWORD cb, LPDWORD lpcNeeded);
为此。
typedef DWORD(__stdcall* EnumModules)(HANDLE hprocess, HMODULE* moduleHandles, DWORD cb, LPDWORD lpcNeeded);
有关更多信息,您可以参考此
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句