DLL中可以动态分配内存吗?解决思路
DLL中可以动态分配内存吗?
做了一个全局HOOK,代码是这样。
#include "windows.h"
HHOOK g_hKeyboard = NULL;
#pragma data_seg("pubData")
HWND g_hWnd = NULL;
char ** g_pszPath = NULL;
int g_nPathCount = 0;
#pragma data_seg()
#pragma comment(linker,"/section:pubData,RWS")
LRESULT CALLBACK KeyboardProc(int nCode,WPARAM wParam,LPARAM lParam)
{
if(nCode == HC_ACTION)
{
if(wParam == VK_F2)
{
for(int nCounter=0;nCounter<g_nPathCount;nCounter++)
{
::MessageBox(g_hWnd,g_pszPath[nCounter],NULL,MB_OK); //没有显示该对话框
}
return 1;
}
}
return CallNextHookEx(g_hKeyboard,nCode,wParam,lParam);
}
_declspec(dllexport) void SetHook(HWND hWnd,char ** pszPath,int nCount)
{
g_hWnd = hWnd;
g_nPathCount = nCount;
g_pszPath = (char**)malloc(nCount*sizeof(char*));
for(int nCounter=0;nCounter<nCount;nCounter++)
{
g_pszPath[nCounter] = (char*)malloc(MAX_PATH);
strcpy(g_pszPath[nCounter],pszPath[nCounter]);
}
g_hShell = ::SetWindowsHookEx(WH_KEYBOARD,KeyboardProc,::GetModuleHandle("Hook"),0);
}
然后用外部程序调用SetHook(),可是运行后却没有对话框显示出来,这是怎么回事呢?
------解决方案--------------------
分配是没问题的,但是你考虑一下,你在进程1中分配的内存,其地址是一个虚拟地址,在另外一个进程中毫无意义,因此在另外一个进程中是不能使用的
对于这种情况,使用的方法是
1. 创建一个命名file mapping作为分配的内存
2. 在共享数据区中使用数组下标而不是指针来访问内存
3. 所有进程都打开这个file mapping,然后根据下标去访问
做了一个全局HOOK,代码是这样。
#include "windows.h"
HHOOK g_hKeyboard = NULL;
#pragma data_seg("pubData")
HWND g_hWnd = NULL;
char ** g_pszPath = NULL;
int g_nPathCount = 0;
#pragma data_seg()
#pragma comment(linker,"/section:pubData,RWS")
LRESULT CALLBACK KeyboardProc(int nCode,WPARAM wParam,LPARAM lParam)
{
if(nCode == HC_ACTION)
{
if(wParam == VK_F2)
{
for(int nCounter=0;nCounter<g_nPathCount;nCounter++)
{
::MessageBox(g_hWnd,g_pszPath[nCounter],NULL,MB_OK); //没有显示该对话框
}
return 1;
}
}
return CallNextHookEx(g_hKeyboard,nCode,wParam,lParam);
}
_declspec(dllexport) void SetHook(HWND hWnd,char ** pszPath,int nCount)
{
g_hWnd = hWnd;
g_nPathCount = nCount;
g_pszPath = (char**)malloc(nCount*sizeof(char*));
for(int nCounter=0;nCounter<nCount;nCounter++)
{
g_pszPath[nCounter] = (char*)malloc(MAX_PATH);
strcpy(g_pszPath[nCounter],pszPath[nCounter]);
}
g_hShell = ::SetWindowsHookEx(WH_KEYBOARD,KeyboardProc,::GetModuleHandle("Hook"),0);
}
然后用外部程序调用SetHook(),可是运行后却没有对话框显示出来,这是怎么回事呢?
------解决方案--------------------
分配是没问题的,但是你考虑一下,你在进程1中分配的内存,其地址是一个虚拟地址,在另外一个进程中毫无意义,因此在另外一个进程中是不能使用的
对于这种情况,使用的方法是
1. 创建一个命名file mapping作为分配的内存
2. 在共享数据区中使用数组下标而不是指针来访问内存
3. 所有进程都打开这个file mapping,然后根据下标去访问