是否可以在Python程序中调用VB6编写的函数?附实际代码场景
结论
该需求完全可以实现,常见有两种实现思路:直接用Python原生逻辑复现INI_IO功能,或者封装原VB6函数为COM组件供Python调用。
方案1:Python原生实现INI_IO功能(推荐,无需依赖VB6运行环境,部署更简单)
你提到的INI_IO是VB6场景下常见的INI配置读写封装函数,参数通常为(节名, 键名, 默认值, 是否写入模式),直接调用Windows系统API即可实现完全一致的逻辑,无需复用原VB6代码。
实现代码如下:
import ctypes from ctypes import wintypes # 加载Windows内置INI操作API kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) GetPrivateProfileString = kernel32.GetPrivateProfileStringW GetPrivateProfileString.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD, wintypes.LPCWSTR] GetPrivateProfileString.restype = wintypes.DWORD WritePrivateProfileString = kernel32.WritePrivateProfileStringW WritePrivateProfileString.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPCWSTR] WritePrivateProfileString.restype = wintypes.BOOL def INI_IO(section: str, key: str, default: str, is_write: bool, ini_path: str = "config.ini") -> str: if is_write: # 写入模式:将默认值写入对应配置项 WritePrivateProfileString(section, key, default, ini_path) return default else: # 读取模式:读取配置项,不存在则返回默认值 buf = wintypes.create_unicode_buffer(2048) GetPrivateProfileString(section, key, default, buf, 2048, ini_path) return buf.value
你原有业务代码适配修改示例(同步替换VB6专属语法):
import os import sys from datetime import datetime import pyodbc def connectMain(): # 替代VB6的App.Path属性:获取当前脚本所在目录 app_root = os.path.dirname(os.path.abspath(__file__)) AppPath = INI_IO("GLOBAL", "AppPath", app_root, True) if AppPath == "": AppPath = "" # 替代VB6的Command属性:获取命令行入参 command_arg = sys.argv[1] if len(sys.argv) > 1 else "" JobTyp = int(command_arg) if command_arg.isnumeric() else 0 # 替代VB6的Now属性:获取当前时间 AktDate = datetime.now() server = '' Driver = '' Database = '' uid= '' pwd = '' connection = pyodbc.connect(f"Driver={{{Driver}}};" f"Server = {server};" f"Database = {Database};" f"uid = {uid};" f"pwd = {pwd};") print("S", "Start", f"JobTyp = {JobTyp}")
方案2:封装原VB6函数为COM组件供Python调用
如果必须复用原有VB6编写的INI_IO逻辑,可按以下步骤操作:
- 打开VB6新建ActiveX DLL项目,命名为
VB6FuncLib - 新建类模块命名为
INIUtil,将原有INI_IO函数代码写入该模块,设置为公共函数 - 生成DLL文件,管理员权限运行cmd执行
regsvr32 VB6FuncLib.dll注册组件 - Python安装
pywin32库后即可调用,示例代码:
import win32com.client # 加载已注册的VB6 COM组件 vb6_tool = win32com.client.Dispatch("VB6FuncLib.INIUtil") # 调用原VB6编写的INI_IO函数 AppPath = vb6_tool.INI_IO("GLOBAL", "AppPath", "你的目标路径", True)
注意:该方案依赖VB6运行环境,且32/64位必须匹配:如果VB6生成的是32位DLL,Python必须使用32位版本,否则会调用失败,部署时也需要提前在目标机器注册COM组件,非必要优先选择方案1。
内容的提问来源于stack exchange,提问作者avinash uriday
相关产品推荐
相关产品推荐

