VB6+Python混合编程(COM组件)

Python的方便不用说,VB6做GUI的简单程度更不用说。二者混合编程的需求一直非常旺盛,但我苦苦搜寻了很久,始终未找到合适的解决方案。
在很长一段时间内,我都是通过创建、读取、删除临时文件来在VB程序和Python程序间传递信息,麻烦,且低级。(如下)
比如下面是一个典型的处理流程

 

1. VB创建需要处理的文本please.txt,并调用Python

 

2. Python读取、处理文本,并将处理后的文本保存为ok.txt

 

3. VB在执行上面语句后进入死循环,等待ok.txt生成,完成后读取,继续流程

 

诸位请看,是不是非常符合麻烦、低级的描述?但没有更好的解决方案,只有如此。

----激动人心的分界线-----

后来发现了一本书(python programming on win32,有兴趣的找来看),终于让我发现了解决方法。COM组件!

COM is a technology from Microsoft that allows objects to communicate without the need for either object to know any details about the other, even the language it's implemented in.

看看本书某章节的总结:

We have seen examples of the various data types that can be passed back and forth between the two languages: numbers, strings, and arrays. The ability to pass multidimensional arrays allows you to move large amounts of data between the two languages without writing a lot of conversion code.

也不用说很多,不想看书的,看看下面这个我从书中摘抄的简短例子,就能知道该方法的核心之处。
在python里:

#需要先安装pipywin32模块
class PythonUtilities:

    _public_methods_=['SplitString']
    _reg_progid_='PythonDemos.Utilities'

    # 使用"print (pythoncom.CreateGuid())" 得到一个自己的clsid,不要用下面这个!!
    _reg_clsid_='{5FCAC95E-653A-484C-8568-A02D5E0256E8}'

    def SplitString(self, val, item=None):
        import string 
        if item !=None: 
            item=str(item)
        val=str(val)
        return val.split(item)

if __name__=='__main__':
    print ('Registering COM server...')
    import win32com.server.register
    win32com.server.register.UseCommandLine(PythonUtilities)

在VB里:

Private Sub Form_Load()
    Set PythonUtils = CreateObject("PythonDemos.Utilities")
    response = PythonUtils.SplitString("Hello from VB")
    For Each Item In response
        MsgBox Item
    Next
End Sub

完成后在cmd中使用(py_name是上面python文件的名称)

> python py_name.py --unregister

注销COM,保证电脑纯净。
多余的不用说了,一试便知,这点代码足以解决诸多混合编程的难题。

该方法不仅适用于VB+Python,Office,Delphi,C++等等,均可使用。


 

  • 4
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值