DLL调用方式:
- 静态调用(编译时链接DLL)
- 动态调用(运行时显示调用)
代码如下:
- DLL
- DLL的编译将生成DLL和LIB两个文档(TestDLL.dll、TestDLL.lib)。
- LIB文档是在编译时用来链接DLL的,称为引用链接库。
#include <windows.h>
// Export this function
extern "C" __declspec(dllexport) double AddNumbers(double a, double b);
// DLL initialization function
BOOL APIENTRY
DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
return TRUE;
}
// Function that adds two numbers
double
AddNumbers(double a, double b)
{
return a + b;
}
- 静态调用
- TestDLL.lib拷至编译目录下
- TestDLL.dll拷至exe目录下
#include <windows.h>
#include <stdio.h>
#pragma comment(lib,"TestDLL.lib") //链接引用链接库
// Import function that adds two numbers
extern "C" __declspec(dllimport)double AddNumbers(double a, double b);
int
main(int argc, char **argv)
{
double result = AddNumbers(1, 2);
printf("The result was: %f\n", result);
system("pause");
return 0;
}
- 动态调用
- TestDLL.dll拷至exe目录下
- 无需TestDLL.lib
#include <windows.h>
#include <stdio.h>
// DLL function signature
typedef double (*importFunction)(double, double);
int
main(int argc, char **argv)
{
importFunction addNumbers;
double result;
// Load DLL file
HINSTANCE hinstLib = LoadLibrary(L"TestDLL.dll");
if (hinstLib == NULL) {
printf("ERROR: unable to load DLL\n");
return 1;
}
// Get function pointer
addNumbers = (importFunction)GetProcAddress(hinstLib, "AddNumbers");
if (addNumbers == NULL) {
printf("ERROR: unable to find DLL function\n");
return 1;
}
// Call function.
result = addNumbers(1, 2);
// Unload DLL file
FreeLibrary(hinstLib);
// Display result
printf("The result was: %f\n", result);
system("pause");
return 0;
}
- 动态调用失败原因:
- 调用约定不匹
- 导出函数名被修改(可通过Depends.Exe查看导出函数名)
- 相应LIB或DLL未拷至相应目录下