我必须将 HWND 变量从主程序传递给 DLL 导出的函数。变量称为 mainHwnd,DLL 以这种方式定义:
mydll.h
#ifdef MYDLL_EXPORTS
#define MYDLL_API extern "C" __declspec(dllexport)
#else
#define MYDLL_API extern "C" __declspec(dllimport)
#endif
MYDLL_API HWND mainHwnd;
MYDLL_API void testFunction(void);
MYDLL_API LRESULT CALLBACK mouseProc(int nCode, WPARAM wParam, LPARAM lParam);
mydll.cpp
#include "stdafx.h"
#include "mydll.h"
#include <string>
#define CLASSNAMELEN 5
MYDLL_API HWND mainHwnd = 0;
// This is an example of an exported function.
MYDLL_API void testFunction(void)
{
MessageBox(NULL, (LPCWSTR)L"Test", (LPCWSTR)L"Test", MB_OK);
}
MYDLL_API LRESULT CALLBACK mouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
// processes the message
if(nCode >= 0)
{
if(wParam != NULL && (wParam == WM_RBUTTONDOWN || wParam == WM_RBUTTONUP))
{
std::wstring s;
MessageBox(NULL, (LPCWSTR)L"Captured mouse right button", (LPCWSTR)L"Test", MB_OK);
MOUSEHOOKSTRUCT *m = (MOUSEHOOKSTRUCT*) lParam;
GetClassName(m->hwnd, (LPWSTR) s.c_str(), CLASSNAMELEN);
if(s == L"Edit")
SendMessage(mainHwnd, WM_APP, 0, (LPARAM) lParam);
}
}
// calls next hook in chain
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
主程序
MYDLL_API HWND mainHwnd;
...
case WM_CREATE:
{
// now it will load DLL and set up hook procedure for mouse events
// declares local variables
HOOKPROC hkprcMouseProc;
HINSTANCE hinstDLL;
HHOOK hhookMouseProc;
// loads DLL
if((hinstDLL = LoadLibrary(TEXT("C:\\Users\\Francesco\\Dropbox\\poli\\bi\\not\\pds\\sp\\wk5\\lsp5\\Debug\\mydll.dll"))) == NULL)
{
MessageBox(hWnd, (LPCWSTR)L"Error loading DLL", (LPCWSTR)L"Error", MB_OK | MB_ICONERROR);
break;
}
// saves main window handle for DLL functions
mainHwnd = hWnd;
...
编译我得到
error LNK2001: unresolved external symbol __imp__mainHwnd
在使用 dumpbin /exports mydll.dll 时,我得到全局变量名被破坏为:
mainHwnd = _mainHwnd
我在谷歌上浏览了很多页面都没有结果。也许有一个概念错误..谢谢