什么是DLL文件?
DLL(Dynamic Link Library,动态链接库)是Windows操作系统中的一种共享库文件格式。它包含可由多个程序同时使用的代码和数据,有助于减少内存占用并实现代码复用。
DLL文件可以包含函数、类、资源(如图标、位图)等,常见的扩展名为.dll。
调用DLL的主要方式
调用DLL有两种主要方式:隐式链接(静态加载)和显式链接(动态加载)。
- 隐式链接:程序启动时自动加载DLL,通过头文件和导入库(.lib)调用函数。
- 显式链接:程序运行时手动加载DLL,使用
LoadLibrary和GetProcAddress等API。
C/C++中调用DLL(显式链接)
以下是使用Windows API显式加载并调用DLL函数的示例:
#include <windows.h>
#include <iostream>
int main() {
// 加载DLL
HINSTANCE hDll = LoadLibrary(L"example.dll");
if (hDll == NULL) {
std::cout << "无法加载DLL文件!" << std::endl;
return 1;
}
// 获取函数指针
typedef int (*AddFunc)(int, int);
AddFunc add = (AddFunc)GetProcAddress(hDll, "add");
if (add == NULL) {
std::cout << "无法找到函数!" << std::endl;
FreeLibrary(hDll);
return 1;
}
// 调用函数
int result = add(5, 3);
std::cout << "结果:" << result << std::endl;
// 释放DLL
FreeLibrary(hDll);
return 0;
}
注意:编译时需要链接
kernel32.lib,并在项目设置中包含Windows头文件。
C#中调用DLL(使用DllImport)
C#可以通过DllImport特性调用非托管DLL中的函数:
using System;
using System.Runtime.InteropServices;
class Program {
// 声明外部函数
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int MessageBox(IntPtr hWnd, string lpText, string lpCaption, uint uType);
static void Main() {
// 调用DLL函数
MessageBox(IntPtr.Zero, "Hello from DLL!", "提示", 0);
}
}
Python中调用DLL
Python可通过ctypes库调用DLL:
from ctypes import *
# 加载DLL
dll = CDLL("example.dll")
# 调用函数
result = dll.add(10, 20)
print("结果:", result)
常见问题与注意事项
- 确保DLL文件路径正确,或放置在系统可搜索的目录中。
- 注意32位与64位程序的兼容性问题。
- 调用后应释放资源,避免内存泄漏。
- 函数名称可能被修饰(name mangling),需使用
extern "C"防止C++名称修饰。 - 调试时可使用Dependency Walker等工具查看DLL导出函数。