C或C++编写的程序效率非常高,有些复杂的计算python不如C或C++程序,所以有时使用python调用C或C++编写编译为 DLL 的文件来处理问题,那 python 如何调用dll文件中的函数呢?
一,生成 DLL 文件,
假设C或C++编写文件名为userDevDll01.cpp的内容如下,文件编译输出dll文件的userDevDll01.dll的内容
// 文件编译输出dll文件的userDevDll01.dll的内容,可定义更多复杂业务逻辑 #include <stdio.h> __declspec(dllexport) int fun01(int a, int b) { return a * b; }编译生成的DLL 文件存放:F:\userDllFiles\userDevDll01.dll
二,在 python 中调用 DLL 文件
1,使用 python 的 ctypes 模块操作DLL,
2,加载 DLL 文件,
3,定义 DLL 的入参的数据类型和返回值的数据类型,
4,python 调用的 DLL 中的方法
参考如下例子:
# -*- coding: UTF-8 -*- # ======================================== # @ProjectName: pythonws001 # @Filename: call_dll.py # @Copyright www.637hulian.com # @Author: shenzhennba(Administrator) # @Version 1.0 # @Since 2025/12/13 15:52 # ======================================== # python调用dll文件 # ======================================== # 1.导入ctypes模块 import ctypes import logging import os import com.pro001.log.pro_log_config as pro_log_config # 调用配置函数,通常在模块加载时调用 pro_log_config.setup_logging() # 获取日志对象和是指各种输出处理器, # 每个模块将有自己的日志记录器,并且可以通过模块名来区分日志消息的来源。 logger = logging.getLogger(__name__) def call_dll_fun01(dll_full_path): """ 调用指定路径的dll中的函数 """ if not os.path.exists(dll_full_path): logging.info(f'dll文件不存在: {dll_full_path}') return None try: # 2.加载dll文件 lib01 = ctypes.WinDLL(dll_full_path) #lib01 = ctypes.cdll.LoadLibrary(dll_full_path) # 3,指定dll中的函数fun01返回值类型和参数类型 lib01.fun01.restype = ctypes.c_int lib01.fun01.argtypes = [ctypes.c_int, ctypes.c_int] # 4.调用dll中的函数 ret = lib01.fun01(10, 20) logging.info(f'调用dll函数fun01返回值:{ret}') return ret except Exception as e: logging.error(f'调用dll函数fun01异常:info:\n{e}') return None def main(): """ 主函数 """ # 假设C或C++编写的dll文件位于如下路径 dll_full_path = r'F:\userDllFiles\userDevDll01.dll' v = call_dll_fun01(dll_full_path) print(f'call dll fun01: {v}') if __name__ == '__main__': main()