Python and VB6


Author: Dave
Date: 11.09.17 - 6:01am



Ok..so there are a ton of python libraries out there I dont want to immediately port over to vb6. How do we communicate between python code and vb6?

Let me start by saying part of me hates this because its pretty hackish and requires dependencies and moons in alignment with packages etc. So this is just for one offs, at present I would never distribute code that ran like this, but with that said I may still need to do it to accomplish a research goal.

So here are our options as I see it so far: I was pleased to see python had support for COM, and it seems to work ok...but it also took a bit of fussing and fighting to get it going. Here are some tips on vb6 and Python over COM
  • You run the python script once normally from the command line as admin to get it to register itself.
  • I then had to update the following reg key manually:
        HKLM/SOFTWARE/Classes/CLSID/{41E24E95-D45A-11D2-852C-204C4F4F5020}/InprocServer32
        HKLM/SOFTWARE/Classes/CLSID/{41E24E95-D45A-11D2-852C-204C4F4F5021}/InprocServer32
        default = C:/Python27/Lib/site-packages/pywin32_system32/pythoncomloader27.dll
    
    by default they only set the dll name and not the full path so it was failing to load.

  • FIXED see below*: once a python com object is loaded into memory changes to the file do not seem to take..you have to close the vb6 ide and restart it. The other way around this is to just always compile and run the exe which sucks for debugging the vb side. I am not sure why this happens yet or if it can be avoided.
  • any errors in your python script or callback it just silently dies you seem to have to debug everything blindly. this includes byval/byref etc not helpful. This necessitated me debugging everything with msgboxes :(
In the end I was able to get the following demos working:
  • IPC out of process demo using WM_COPYDATA
  • CreateObject of a python COM object from VB6
  • python function taking in a string and returning a variant array
  • python calling a vb6 addressof callback and passing in a string and int
  • python returning a new instance of a vb6 usable python COM object
  • get/set a property on a python COM object
  • pass VB COM object to python and:
    • python calls sub on vb object
    • python does property get to get object reference for form1.Text1
    • python does property get for form1.Text1.Text
Those were the first major tests I could think of to get my feet wet. The process and debugging seems a little delicate and hairy with nuances and poor debugging experience.

The IPC went smoothly and of course the stdout/file out will go smooth.

As for embedding python and using it from vb6 directly as the dll. This was my first thought on the way to go and I may play with it, but it will be the most work. The python dll is not stdcall so we will need a C shim to access its api and provide wrappers. This is probably the only way I would consider this technique for distribution with an app because I could control the environment.




*BugFix for cached classes:

So apparently it is by design that once a class is loaded in a process it is cached and changes to the file do not take effect until the module is manually reloaded or the you get a new process.

For our test code this matters while working in the vb6 IDE since we are doing development work and probably want to edit the python source but are always calling it from the same IDE process instance.

So here is the fix..

In the python class we add an exec method:

def Exec(self, exp):
        """Execute a statement.
        """
        if type(exp) not in [str, unicode]:
            raise Exception(desc="Must be a string",scode=winerror.DISP_E_TYPEMISMATCH)
        exec str(exp) in self.dict   


Then in VB we can add the following code:

If IsIde() And GetModuleHandle("python27.dll") <> 0 Then
        dbg "found python in memory still..trying to reload module in case there were changes..."
        reload "PythonDemos"
    End If

Function reload(moduleName As String) As String
    On Error Resume Next
    Dim cmd As String
    cmd = Replace("import %1;reload(%1)", "%1", moduleName)
    Set o = CreateObject("PythonDemos.Utilities")
    o.exec cmd
    Text1 = Replace(Err.Description, vbLf, vbCrLf)
End Function





Comments: (0)

 
Leave Comment:
Name:
Email: (not shown)
Message: (Required)
Math Question: 27 + 10 = ? followed by the letter: G 



About Me
More Blogs
Main Site
Posts: (year)
2024 (1)
     RegJump Vb
2023 (9)
     VB6 Virtual Files
     File handles across dlls
     python abort / script timeout
     py4vb
     VB6 Python embed w/debugger
     python embedding
     VB6 IDE Enhancements
     No Sleep
     A2W no ATL
2022 (4)
     More VB6 - C data passing
     Vb6 Asm listing
     Byte Array C to VB6
     Planet Source Code DVDs
2021 (2)
     Obscure VB
     VB6 IDE SP6
2020 (4)
     NTFileSize
     BSTR from C Dll to VB
     Cpp Memory Manipulation
     ActiveX Binary Compatability
2019 (5)
     Console tricks
     FireFox temp dir
     OCX License
     Extract substring
     VB6 Console Apps
2018 (6)
     VB6 UDTs
     VB6 Debugger View As Hex tooltips
     VB6 - C Share registry data
     VB6 Addin Missing Menus
     VB6 Class Init Params
     VB6 isIn function
2017 (6)
     Python and VB6
     Python pros and cons
     download web Dir
     vc rand in python
     VB6 Language Enhancement
     Register .NET as COM
2016 (22)
     VB6 CDECL
     UDT Tricks pt2
     Remote Data Extraction
     Collection Extender
     VB6 FindResource
     CDO.Message
     DirList Single Click
     Reset CheckPoint VPN Policy
     VB6 BSTR Oddities Explained
     SafeArrays in C
     BSTR and Variant in C++
     Property let optional args
     Misc Libs
     Enum Named Pipes
     Vb6 Collection in C++
     VB6 Overloaded Methods
     EXPORT FUNCDNAME Warning
     VB6 Syncronous Socket
     Simple IPC
     VB6 Auto Resize Form Elements
     Mach3 Automation
     Exit For in While
2015 (15)
     C# self register ocx
     VB6 Class Method Pointers
     Duktape Debug Protocol
     QtScript 4 VB
     Vb6 Named Args
     vb6 Addin Part 2
     VB6 Addin vrs Toolbars
     OpenFile Dialog MultiSelect
     Duktape Example
     DukTape JS
     VB6 Unsigned
     .Net version
     TitleBar Height
     .NET again
     VB6 Self Register OCXs
2014 (25)
     Query Last 12 Mos
     Progid from Interface ID
     VB6 to C Array Examples
     Human Readable Variant Type
     ScriptBasic COM Integration
     CodeView Addin
     ScriptBasic - Part 2
     Script Env
     MSCOMCTL Win7 Error
     printf override
     History Combo
     Disable IE
     API Hooking in VB6
     Addin Hook Events
     FastBuild Addin
     VB6 MemoryWindow
     Link C Obj Files into VB6
     Vb6 Standard Dlls
     CStr for Pascal
     Lazarus Review
     asprintf for VS
     VB6 GlobalMultiUse
     Scintilla in VB6
     Dynamic Highlight
     WinVerifyTrust, CryptMsgGetParam VB6
2013 (4)
     MS GLEE Graphing
     printf for VB6
     C# App Config
     Tero DES C# Test
2012 (10)
     VC 2008 Bit Fields
     Speed trap
     C# Db Class Generator
     VB6 vrs .NET (again)
     FireFox Whois Extension
     git and vb6
     Code Additions
     Compiled date to string
     C# ListView Sorter
     VB6 Wish List
2011 (7)
     C# Process Injection
     CAPTCHA Bots
     C# PE Offset Calculator
     VB6 Async Download
     Show Desktop
     coding philosophy
     Code release
2010 (11)
     Dll Not Found in IDE
     Advanced MSScript Control
     random tip
     Clipart / Vector Art
     VB6 Callback from C#
     Binary data from VB6 to C#
     CSharp and MsScriptControl
     HexDumper functions
     Js Beautify From VB6 or C#
     vb6 FormPos
     Inline Asm w VB6
2009 (3)
     The .NET Fiasco
     One rub on computers
     Universal extractor