什么是DLL文件?
DLL(Dynamic Link Library,动态链接库)是 Windows 系统中用于共享代码和资源的文件格式。通过调用 DLL,多个程序可以共用同一段代码,节省内存并便于维护。
C/C++ 中调用 DLL
在 C/C++ 中,可以通过 LoadLibrary 和 GetProcAddress 动态加载 DLL:
#include <windows.h>
#include <iostream>
typedef int (*AddFunc)(int, int);
int main() {
HMODULE hDll = LoadLibrary(L"mylib.dll");
if (hDll) {
AddFunc add = (AddFunc)GetProcAddress(hDll, "Add");
if (add) {
std::cout << "Result: " << add(3, 4) << std::endl;
}
FreeLibrary(hDll);
}
return 0;
}
C# 中调用 DLL
使用 DllImport 特性可直接声明外部函数:
using System;
using System.Runtime.InteropServices;
class Program {
[DllImport("mylib.dll")]
public static extern int Add(int a, int b);
static void Main() {
Console.WriteLine("Result: " + Add(3, 4));
}
}
Python 中调用 DLL
通过 ctypes 模块加载 DLL 并调用函数:
import ctypes
dll = ctypes.CDLL('./mylib.dll')
dll.Add.argtypes = (ctypes.c_int, ctypes.c_int)
dll.Add.restype = ctypes.c_int
result = dll.Add(3, 4)
print("Result:", result)
注意事项
- 确保 DLL 文件与调用程序架构一致(x86/x64)。
- 导出函数需使用
__declspec(dllexport)声明(C/C++)。 - 注意调用约定(如
__stdcallvs__cdecl)。