为什么我不能访问我的DLL功能
-
28-09-2019 - |
题
我正在尝试使用动态加载DLL LoadLibrary()
, ,它有效,但是我无法在我要调用的dll中获取功能的地址。
DLL函数:(在CPP文件中)
_declspec(dllexport) void MyDllFunc()
{
printf("Hello from DLL");
}
通话代码:
typedef void (*MyDllFuncPtr)();
int _tmain(int argc, _TCHAR* argv[])
{
HINSTANCE LoadMe;
LPCWSTR str = L"C:\\Users\\Tony\\Documents\\Visual Studio 2008\\Projects\\DLL Loading\\Release\\MyDll.dll";
LoadMe = LoadLibrary(str);
if(LoadMe != 0)
printf("Successfully Loaded!\r\n");
else
printf("Loading Failed \r\n" );
MyDllFuncPtr func;
func = (MyDllFuncPtr)GetProcAddress(LoadMe, "MyDllFunc");
if (func != NULL)
func();
FreeLibrary(LoadMe);
}
功能返回零!!!
我究竟做错了什么?
这是一个Win32控制台项目。
解决方案
写
extern "C" _declspec(dllexport) void MyDllFunc()
其他提示
你这样做是错的。 __declSpec(dllexport)与__declspec(dllimport)对。
#1: In the DLL, declare the function's prototype with __declspec(dllexport).
#2: In the .exe, declare the function's prototype with __declspec(dllimport).
#3: Compile the .dll. You should also get a .lib file.
#4: Link the .exe with the .lib, and compile.
#5: Success.
当您使用__declSpec(dllimport)和__declSpec(dllexport)时,您无需触摸Winapi功能即可加载DLL。 dllimport/导出为您完成了所有功能。此外,您不需要外观。
您的导出功能名称正在 装饰 使用时 __declSpec(dllexport), ,您可以使用 外部“ C”, 但是,您需要使用一个符号,这将不会完全没有装饰 def文件 并将其导出为命名符号,否则您需要使用 GetProcAddress
使用修理/装饰的符号名称,使用时短时 extern "C"
.
如果DLL是作为C ++ DLL构建的,则其功能的名称将会更改。这是编译器的依赖性。我强烈建议将其制作为C DLL(C接口+ C ++胆量)。我现在没有一个例子,但是您应该能够在网上找到一些东西。
不隶属于 StackOverflow