杰瑞科技汇

Python如何调用DLL?

在 Python 中调用 DLL(动态链接库)主要有以下几种方式,适用于不同场景:

Python如何调用DLL?-图1
(图片来源网络,侵删)

使用 ctypes(标准库,无需额外安装)

ctypes 是 Python 内置的库,用于调用 C 兼容的 DLL/共享库。

基本步骤

  1. 加载 DLL:使用 ctypes.CDLL()ctypes.WinDLL()(Windows)。
  2. 定义函数参数和返回类型:通过 argtypesrestype 指定。
  3. 调用函数:直接通过函数对象调用。

示例代码

from ctypes import *
# 加载 DLL(假设当前目录下有 mylib.dll)
mylib = CDLL('./mylib.dll')
# 定义函数参数和返回类型
mylib.add_numbers.argtypes = [c_int, c_int]  # 两个 int 参数
mylib.add_numbers.restype = c_int            # 返回 int
# 调用函数
result = mylib.add_numbers(5, 3)
print(f"Result: {result}")  # 输出: Result: 8

处理字符串参数

# 假设 DLL 中有函数 void greet(const char* name)
mylib.greet.argtypes = [c_char_p]  # C 风格字符串
mylib.greet.restype = None         # 无返回值
mylib.greet(b"Hello")  # 注意:Python 3 中需用 bytes

结构体/指针处理

from ctypes import Structure, POINTER
class Point(Structure):
    _fields_ = [("x", c_int), ("y", c_int)]
# 假设函数返回 Point 结构体
mylib.get_point.restype = Point
point = mylib.get_point()
print(f"Point: ({point.x}, {point.y})")

使用 pythonnet(调用 .NET DLL)

如果需要调用 .NET 程序集(如 C#、VB.NET 编写的 DLL),需安装 pythonnet

安装

pip install pythonnet

示例代码

import clr
# 加载 .NET 程序集(需指定路径)
clr.AddReference("MyAssembly.dll")  # 替换为你的 DLL 路径
# 导入命名空间和类
from MyNamespace import MyClass
# 创建实例并调用方法
obj = MyClass()
result = obj.Method1(10, 20)
print(result)

使用 CFFI(调用 C 库)

CFFIctypes 更灵活,适合复杂 C 库交互。

安装

pip install cffi

示例代码

from cffi import FFI
ffi = FFI()
# 声明 C 函数和类型
ffi.cdef("""
    int add_numbers(int a, int b);
""")
# 加载 DLL
lib = ffi.dlopen("./mylib.dll")
# 调用函数
result = lib.add_numbers(5, 3)
print(f"Result: {result}")

使用 ctypes 处理回调函数

from ctypes import CFUNCTYPE, c_int
# 定义回调函数类型
CALLBACK = CFUNCTYPE(c_int, c_int)
def callback(x):
    print(f"Callback called with: {x}")
    return x * 2
# 将 Python 函数转为 C 回调
c_callback = CALLBACK(callback)
# 假设 DLL 中有 void register_callback(int (*func)(int))
mylib.register_callback(c_callback)

常见问题

  1. 找不到 DLL

    Python如何调用DLL?-图2
    (图片来源网络,侵删)
    • 确保路径正确(或放在 PATH 环境变量中)。
    • Windows 下可尝试 LoadLibrary("mylib.dll") 并检查错误。
  2. 参数类型错误

    • 确保 argtypesrestype 与 C 函数声明一致。
  3. 内存管理

    • 使用 ctypes 时需手动管理内存(如 c_void_p 的释放)。
  4. Unicode 字符串

    • Windows 下用 c_wchar_p 处理宽字符。

方法 适用场景 优点 缺点
ctypes 标准 C DLL,简单调用 无需安装,Python 内置 复杂类型处理较繁琐
pythonnet .NET 程序集(C#/VB.NET) 直接调用 .NET 代码 仅限 Windows,需安装
CFFI 高性能 C 库,复杂交互 更灵活,支持回调 需额外安装

根据需求选择合适的方法,ctypes 适合大多数简单场景,pythonnet 专攻 .NET,CFFI 提供更高级的 C 库交互能力。

Python如何调用DLL?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇