Expose methods and properties via fully dynamic dispatch.
| 60 | |
| 61 | |
| 62 | class _Dispatch: |
| 63 | """Expose methods and properties via fully dynamic dispatch.""" |
| 64 | |
| 65 | _comobj: automation.IDispatch |
| 66 | _ids: dict[str, int] |
| 67 | _methods: set[str] |
| 68 | |
| 69 | def __init__(self, comobj: "ctypes._Pointer[automation.IDispatch]"): |
| 70 | self.__dict__["_comobj"] = comobj |
| 71 | # Tiny optimization: trying not to use GetIDsOfNames more than once |
| 72 | self.__dict__["_ids"] = {} |
| 73 | self.__dict__["_methods"] = set() |
| 74 | |
| 75 | def __enum(self) -> automation.IEnumVARIANT: |
| 76 | e: IUnknown = self._comobj.Invoke(-4) # DISPID_NEWENUM |
| 77 | return e.QueryInterface(automation.IEnumVARIANT) |
| 78 | |
| 79 | def __hash__(self) -> int: |
| 80 | return hash(self._comobj) |
| 81 | |
| 82 | def __getitem__(self, index: Any) -> Any: |
| 83 | enum = self.__enum() |
| 84 | if index > 0: |
| 85 | if 0 != enum.Skip(index): |
| 86 | raise IndexError("index out of range") |
| 87 | item, fetched = enum.Next(1) |
| 88 | if not fetched: |
| 89 | raise IndexError("index out of range") |
| 90 | return item |
| 91 | |
| 92 | def QueryInterface( |
| 93 | self, interface: type[_T_IUnknown], iid: Optional[GUID] = None |
| 94 | ) -> _T_IUnknown: |
| 95 | """QueryInterface is forwarded to the real com object.""" |
| 96 | return self._comobj.QueryInterface(interface, iid) |
| 97 | |
| 98 | def _FlagAsMethod(self, *names: str) -> None: |
| 99 | """Flag these attribute names as being methods. |
| 100 | Some objects do not correctly differentiate methods and |
| 101 | properties, leading to problems when calling these methods. |
| 102 | |
| 103 | Specifically, trying to say: ob.SomeFunc() |
| 104 | may yield an exception "None object is not callable" |
| 105 | In this case, an attempt to fetch the *property*has worked |
| 106 | and returned None, rather than indicating it is really a method. |
| 107 | Calling: ob._FlagAsMethod("SomeFunc") |
| 108 | should then allow this to work. |
| 109 | """ |
| 110 | self._methods.update(names) |
| 111 | |
| 112 | def __getattr__(self, name: str) -> Any: |
| 113 | if name.startswith("__") and name.endswith("__"): |
| 114 | raise AttributeError(name) |
| 115 | # tc = self._comobj.GetTypeInfo(0).QueryInterface(comtypes.typeinfo.ITypeComp) |
| 116 | # dispid = tc.Bind(name)[1].memid |
| 117 | dispid = self._ids.get(name) |
| 118 | if not dispid: |
| 119 | dispid = self._comobj.GetIDsOfNames(name)[0] |
no outgoing calls
no test coverage detected
searching dependent graphs…