This class collects IDL code fragments and eventually writes them into a .IDL file. The compile() method compiles the IDL file into a typelibrary and registers it. A function is also registered with atexit that will unregister the typelib at program exit.
| 9 | |
| 10 | |
| 11 | class TypeLib: |
| 12 | """This class collects IDL code fragments and eventually writes |
| 13 | them into a .IDL file. The compile() method compiles the IDL file |
| 14 | into a typelibrary and registers it. A function is also |
| 15 | registered with atexit that will unregister the typelib at program |
| 16 | exit. |
| 17 | """ |
| 18 | |
| 19 | def __init__(self, lib): |
| 20 | self.lib = lib |
| 21 | self.interfaces = [] |
| 22 | self.coclasses = [] |
| 23 | |
| 24 | def interface(self, header): |
| 25 | itf = Interface(header) |
| 26 | self.interfaces.append(itf) |
| 27 | return itf |
| 28 | |
| 29 | def coclass(self, definition): |
| 30 | self.coclasses.append(definition) |
| 31 | |
| 32 | def __str__(self): |
| 33 | header = ( |
| 34 | """import "oaidl.idl"; |
| 35 | import "ocidl.idl"; |
| 36 | %s {""" |
| 37 | % self.lib |
| 38 | ) |
| 39 | body = "\n".join([str(itf) for itf in self.interfaces]) |
| 40 | footer = "\n".join(self.coclasses) + "}" |
| 41 | return "\n".join((header, body, footer)) |
| 42 | |
| 43 | def compile(self): |
| 44 | """Compile and register the typelib""" |
| 45 | code = str(self) |
| 46 | curdir = os.path.dirname(__file__) |
| 47 | idl_path = os.path.join(curdir, "mylib.idl") |
| 48 | tlb_path = os.path.join(curdir, "mylib.tlb") |
| 49 | if not os.path.isfile(idl_path) or open(idl_path, "r").read() != code: |
| 50 | open(idl_path, "w").write(code) |
| 51 | os.system( |
| 52 | r'call "%%VS71COMNTOOLS%%vsvars32.bat" && ' |
| 53 | r"midl /nologo %s /tlb %s" % (idl_path, tlb_path) |
| 54 | ) |
| 55 | # Register the typelib... |
| 56 | tlib = comtypes.typeinfo.LoadTypeLib(tlb_path) |
| 57 | # create the wrapper module... |
| 58 | comtypes.client.GetModule(tlb_path) |
| 59 | # Unregister the typelib at interpreter exit... |
| 60 | attr = tlib.GetLibAttr() |
| 61 | guid, major, minor = attr.guid, attr.wMajorVerNum, attr.wMinorVerNum |
| 62 | ## atexit.register(comtypes.typeinfo.UnRegisterTypeLib, |
| 63 | ## guid, major, minor) |
| 64 | return tlb_path |
| 65 | |
| 66 | |
| 67 | class Interface: |
no outgoing calls
no test coverage detected
searching dependent graphs…