Friday 9 August 2019

Python MIDL Launcher

If you ever need worked with COM type libraries then you will have no doubt bumped in MIDL which is the Microsoft Interface Definition Language compiler. This is a command line tool but if you want to incorporate it into part of your build process you are going to need to shell or launch the process. I have given a C# launcher Midl here. Also I have given a windows batch file launcher here. Below I give a Python equivalent Midl launcher.

I find this code necessary because I need to alter the environment variables PATH and INCLUDE in order to get MIDL to work. The code below also goes on to load the newly create type library and then register it as this is the majority use case (feel free to omit if not appropriate).

import pythoncom

class MidlLauncher(object):
    @staticmethod
    def CompileTypelib(idlFullFileName):
        from distutils.dep_util import newer
        import os
        import subprocess
        try:
            tlb = os.path.splitext(idlFullFileName)[0] + '.tlb'
            if os.path.isfile(idlFullFileName): 

                if newer(idlFullFileName, tlb):

                    import subprocess, os
                    midl_env = os.environ.copy()
                    
                    midl_env["PATH"] = 'C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\bin\\;' + midl_env["PATH"]
                    mustInclude = ("C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.16299.0\\um\\;" + 
                                          "C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.16299.0\\shared\\;" +
                                          "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319;" )
                    if "INCLUDE" in midl_env:
                        midl_env["INCLUDE"] = mustInclude + midl_env["INCLUDE"]
                    else:
                        midl_env["INCLUDE"] = mustInclude 

                    midl = subprocess.Popen(["C:\\Program Files (x86)\\Windows Kits\\10\\bin\\10.0.16299.0\\x86\\midl.exe", idlFullFileName, "/tlb" , tlb],env=midl_env)
                    midl.wait()

                    print("Registering %s" % (tlb,))
                    tli = pythoncom.LoadTypeLib(tlb)
                    pythoncom.RegisterTypeLib(tli,tlb)
        except Exception as e:
            print("Error: " + str(e) + "\n")

No comments:

Post a Comment