@node-ctypes/comtypes 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +114 -47
- package/dist/automation/dispatch.d.ts +6 -0
- package/dist/automation/dispatch.js +78 -29
- package/dist/automation/members.js +31 -22
- package/dist/automation/variant.d.ts +2 -0
- package/dist/automation/variant.js +38 -1
- package/dist/cli.js +7 -2
- package/dist/client/best.d.ts +6 -0
- package/dist/client/best.js +89 -45
- package/dist/client/constants.js +2 -2
- package/dist/client/dual.d.ts +14 -0
- package/dist/client/dual.js +122 -0
- package/dist/client/dynamic.d.ts +21 -9
- package/dist/client/dynamic.js +123 -18
- package/dist/client/events.js +11 -11
- package/dist/client/index.d.ts +39 -19
- package/dist/client/index.js +124 -17
- package/dist/commethod.js +67 -18
- package/dist/dispmethod.js +26 -5
- package/dist/executor/apartment.d.ts +32 -0
- package/dist/executor/apartment.js +226 -0
- package/dist/executor/classes.d.ts +10 -0
- package/dist/executor/classes.js +18 -0
- package/dist/executor/executor.d.ts +76 -0
- package/dist/executor/executor.js +208 -0
- package/dist/executor/operations.d.ts +29 -0
- package/dist/executor/operations.js +95 -0
- package/dist/index.d.ts +6 -2
- package/dist/index.js +3 -1
- package/dist/interface.d.ts +43 -3
- package/dist/interface.js +28 -8
- package/dist/interfaces/servprov.js +2 -2
- package/dist/low-level/index.d.ts +2 -0
- package/dist/low-level/index.js +1 -0
- package/dist/low-level/native.d.ts +6 -0
- package/dist/low-level/native.js +13 -1
- package/dist/pointer.d.ts +57 -6
- package/dist/pointer.js +233 -9
- package/dist/server/comobject.js +9 -3
- package/dist/server/errorinfo.js +6 -6
- package/dist/server/register.js +5 -0
- package/dist/threads.js +4 -4
- package/dist/tracking.d.ts +2 -0
- package/dist/tracking.js +4 -0
- package/dist/typelib/build.d.ts +5 -0
- package/dist/typelib/build.js +8 -1
- package/dist/typelib/generate.js +14 -11
- package/dist/typelib/getmodule.d.ts +14 -3
- package/dist/typelib/getmodule.js +61 -19
- package/dist/typelib/index.d.ts +1 -1
- package/dist/typelib/index.js +1 -1
- package/dist/typelib/load.js +32 -8
- package/dist/typelib/model.d.ts +3 -0
- package/dist/typelib/model.js +87 -66
- package/dist/typelib/steps.d.ts +12 -0
- package/dist/typelib/steps.js +51 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -6,6 +6,7 @@ Typed Windows COM support for Node.js powered by [node-ctypes](https://www.npmjs
|
|
|
6
6
|
- Windows only at runtime (`ole32.dll`, `oleaut32.dll`). The package imports on Linux and macOS, and GUID/HRESULT/interface definitions work there, so shared code and unit tests run everywhere.
|
|
7
7
|
- Independent package: no native addon of its own, only `node-ctypes`.
|
|
8
8
|
- Client and server side: vtable interfaces with IDL flags, automation (`IDispatch`, `VARIANT`, `SAFEARRAY`), type libraries and code generation, COM objects written in JavaScript, events, LocalServer32 servers.
|
|
9
|
+
- **Asynchronous calls**: methods return promises and run on a dedicated COM thread, so slow objects never block the event loop (or an Electron UI); properties stay synchronous. See [Execution model](#execution-model).
|
|
9
10
|
|
|
10
11
|
```sh
|
|
11
12
|
npm install @node-ctypes/comtypes
|
|
@@ -29,28 +30,28 @@ import { apartment, CreateObject, IPersistFile, ShellLink } from "@node-ctypes/c
|
|
|
29
30
|
using _ = apartment(); // CoInitializeEx(COINIT_APARTMENTTHREADED) ... CoUninitialize()
|
|
30
31
|
|
|
31
32
|
// Vtable interface: the ShellLink coclass gives an IShellLinkW pointer.
|
|
32
|
-
using link = CreateObject(ShellLink);
|
|
33
|
-
link.SetPath("C:\\Windows\\notepad.exe");
|
|
34
|
-
link.SetDescription("Notepad");
|
|
33
|
+
using link = await CreateObject(ShellLink);
|
|
34
|
+
await link.SetPath("C:\\Windows\\notepad.exe");
|
|
35
|
+
await link.SetDescription("Notepad");
|
|
35
36
|
using file = link.QueryInterface(IPersistFile);
|
|
36
|
-
file.Save("C:\\Temp\\notepad.lnk", 1);
|
|
37
|
+
await file.Save("C:\\Temp\\notepad.lnk", 1);
|
|
37
38
|
const text = create_unicode_buffer(260);
|
|
38
|
-
link.GetPath(text, 260, null, 0);
|
|
39
|
+
await link.GetPath(text, 260, null, 0);
|
|
39
40
|
console.log(text.value);
|
|
40
41
|
|
|
41
42
|
// Automation: typed from the type library of the object.
|
|
42
|
-
using dict = CreateObject("Scripting.Dictionary"); // IDictionary
|
|
43
|
-
dict.Add("a", 1);
|
|
44
|
-
console.log(dict.Count, dict.Item("a"));
|
|
43
|
+
using dict = await CreateObject("Scripting.Dictionary"); // IDictionary
|
|
44
|
+
await dict.Add("a", 1); // methods return promises
|
|
45
|
+
console.log(dict.Count, dict.Item("a")); // properties are synchronous
|
|
45
46
|
```
|
|
46
47
|
|
|
47
|
-
Failures throw a `COMError`. Raw methods (`STDMETHOD`)
|
|
48
|
+
Failures reject (or throw, for synchronous members) with a `COMError`. Raw methods (`STDMETHOD`) resolve to the HRESULT (`S_OK`, `S_FALSE`); methods declared with `COMMETHOD` resolve to their output parameters.
|
|
48
49
|
|
|
49
50
|
## Apartments and lifetime
|
|
50
51
|
|
|
51
52
|
### Apartments
|
|
52
53
|
|
|
53
|
-
`CoInitializeEx()` defaults to `COINIT_APARTMENTTHREADED`, like comtypes; Shell and most automation objects require it. `apartment()` initializes and uninitializes with `using`.
|
|
54
|
+
`CoInitializeEx()` defaults to `COINIT_APARTMENTTHREADED`, like comtypes; Shell and most automation objects require it. `apartment()` initializes and uninitializes with `using`. This is the apartment of the JavaScript thread, the **home** apartment; method calls run on the COM executor (see [Execution model](#execution-model)). The Node.js event loop does not pump Win32 messages: calls into in-process STA objects work directly, while incoming calls and events delivered through window messages need a pump (see [Message pump](#message-pump)).
|
|
54
55
|
|
|
55
56
|
### Pointers
|
|
56
57
|
|
|
@@ -81,7 +82,7 @@ declare const object: COMPointer; // or a dispatch object, or a COMObject
|
|
|
81
82
|
// Owner thread (an STA: incoming calls arrive as window messages, so pump).
|
|
82
83
|
using pump = startMessagePump();
|
|
83
84
|
new Worker("./worker.ts", { workerData: { token: marshalInterface(object, IDispatch) } });
|
|
84
|
-
// worker.ts: using _ = apartment(); using proxy = unmarshalDispatch(workerData.token); proxy.Add(1, 2);
|
|
85
|
+
// worker.ts: using _ = apartment(); using proxy = unmarshalDispatch(workerData.token); await proxy.Add(1, 2);
|
|
85
86
|
|
|
86
87
|
// Or register once and get a proxy in any thread, any number of times:
|
|
87
88
|
using table = new GlobalInterfaceTable();
|
|
@@ -90,6 +91,64 @@ const cookie = table.register(object, IDispatch); // table.get(cookie, IFoo) / t
|
|
|
90
91
|
|
|
91
92
|
`marshalInterface` (`CoMarshalInterThreadInterfaceInStream`) returns a single-use token that can be cloned with `postMessage`. `unmarshalInterface(token, IFoo)` and `unmarshalDispatch(token)` consume it; `releaseMarshaled(token)` discards it. `IDispatch` always crosses apartments; custom vtable interfaces need a registered proxy/stub or type library (see [Servers](#servers)).
|
|
92
93
|
|
|
94
|
+
## Execution model
|
|
95
|
+
|
|
96
|
+
**Calls are asynchronous; live access is synchronous.** Methods return promises and run on the **COM executor**, a native thread owned by node-comtypes (a node-ctypes `Executor`, not a libuv worker) in the multithreaded apartment, one call at a time in FIFO order. The event loop stays free while a call runs, however slow the object (an Office application, a remote server, WMI, an application that does not respond).
|
|
97
|
+
|
|
98
|
+
| Asynchronous (`Promise`) | Synchronous |
|
|
99
|
+
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
|
|
100
|
+
| COMMETHOD / STDMETHOD methods, DISPMETHODs, methods of dynamic objects | properties: get, put, putref, parameterized (`dict.Item("a")`, `_get_X` / `_set_X`) |
|
|
101
|
+
| `CreateObject`, `GetObject`, `GetActiveObject` | `QueryInterface`, `AddRef`, `Release`, `using`, `GetBestInterface`, `queryService` |
|
|
102
|
+
| `for await` over collections (`IEnumVARIANT::Next` on the executor) | `for...of`, `VARIANT` conversions, `Constants`, `getModuleSync`, `GetEvents`, generated modules |
|
|
103
|
+
| `GetModule` (in slices on the JavaScript thread, see below) | |
|
|
104
|
+
| `executorCall` (low-level) | the server side: `COMObject` implementations, `fireEvent`, registration; [`sync()`](#synchronous-calls) views |
|
|
105
|
+
|
|
106
|
+
```typescript
|
|
107
|
+
import { apartment, CreateObject, run } from "@node-ctypes/comtypes";
|
|
108
|
+
|
|
109
|
+
using _ = apartment();
|
|
110
|
+
using excel = await CreateObject("Excel.Application", { dynamic: true });
|
|
111
|
+
using books = excel.Workbooks; // property: synchronous
|
|
112
|
+
using book = await books.Add(); // method: on the executor
|
|
113
|
+
for await (const sheet of book.Worksheets) {
|
|
114
|
+
using owned = sheet; // fetched on the executor
|
|
115
|
+
console.log(owned.Name);
|
|
116
|
+
}
|
|
117
|
+
await run(book.SaveAs("C:\\Temp\\a.xlsx"), { signal: AbortSignal.timeout(10_000) });
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
**Objects and apartments.** Objects are created on the executor, so their calls never run on the JavaScript thread. The JavaScript thread keeps its own reference, valid in its home apartment:
|
|
121
|
+
|
|
122
|
+
- a multithreaded home (`apartment(COINIT_MULTITHREADED)`) and agile objects (`IAgileObject`, the free-threaded marshaler) share one reference with the executor;
|
|
123
|
+
- in a single-threaded home, objects are passed through the Global Interface Table: properties are read through a proxy, methods on the executor. This needs interfaces that can be marshaled: `IDispatch`, `[oleautomation]` and dual interfaces with a registered type library, interfaces with a proxy/stub. Dual interfaces that cannot be marshaled are called through `IDispatch` (same members, with their DISPIDs);
|
|
124
|
+
- pointers obtained on the JavaScript thread (`CoCreateInstance`, `QueryInterface` of an STA object, JavaScript `COMObject`s with `_threading_ = "apartment"`) are called on the JavaScript thread, synchronously, while the promise keeps the same shape. Calls passing them as arguments run there too;
|
|
125
|
+
- interface results (out pointers, `VARIANT`s, `SAFEARRAY`s of objects) are handed over to the home apartment before the promise settles.
|
|
126
|
+
|
|
127
|
+
`{ home: true }` creates or binds an object on the JavaScript thread instead (direct calls, no marshaling, but on that thread): in a single-threaded home, use it for objects whose interfaces cannot be marshaled, such as ADSI `IDirectorySearch`, or choose a multithreaded home. Classes this thread registered with `registerClassObject` are created at home automatically.
|
|
128
|
+
|
|
129
|
+
**Cancellation.** `run(promise, { signal })` awaits a COM operation with an `AbortSignal`: on abort it rejects with `signal.reason` and skips the operation's calls still queued on the executor. A call already running completes (COM does not interrupt it).
|
|
130
|
+
|
|
131
|
+
**Lifetime.** The executor starts at the first asynchronous call, keeps the process alive only while calls are pending, and stops at exit. `await finalize()` drains the accepted calls and stops it (a later call starts a new one); `stats()` returns `{ running, pending, completed, generation }`.
|
|
132
|
+
|
|
133
|
+
### Synchronous calls
|
|
134
|
+
|
|
135
|
+
`sync(pointer)` (or `sync(dynamicObject)`) returns a view of the same object whose methods run synchronously on the JavaScript thread, sharing its reference (releasing either releases both): for event handlers, `COMObject` implementations, or code that must not interleave with other JavaScript.
|
|
136
|
+
|
|
137
|
+
Each asynchronous call is a round trip to the executor thread: a typed method costs about 20 µs with its conversions, against 2–4 µs synchronously. That is negligible for most code; `sync()` is there for loops of many fast calls where it adds up.
|
|
138
|
+
|
|
139
|
+
```typescript
|
|
140
|
+
import { CreateObject, sync } from "@node-ctypes/comtypes";
|
|
141
|
+
|
|
142
|
+
using dict = await CreateObject("Scripting.Dictionary");
|
|
143
|
+
sync(dict).Add("a", 1); // S_OK, not a Promise
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Generated modules type both: `XMethods` (promises) for pointers, `XSyncMethods` for `sync()` views.
|
|
147
|
+
|
|
148
|
+
### Electron
|
|
149
|
+
|
|
150
|
+
The main process's JavaScript thread is Chromium's UI thread, already a single-threaded apartment (`CoInitializeEx(COINIT_MULTITHREADED)` there fails with `RPC_E_CHANGED_MODE`); `apartment()` keeps it. Methods run on the executor, so the UI does not freeze; Chromium pumps window messages, so events arrive without `startMessagePump`. Synchronous property reads go through a proxy to the object's apartment: keep them out of tight loops on slow objects. [tests/electron/main.mjs](./tests/electron/main.mjs) checks this in Electron (`electron tests/electron/main.mjs` after a build).
|
|
151
|
+
|
|
93
152
|
## Automation
|
|
94
153
|
|
|
95
154
|
`CreateObject`, `GetObject` and `GetActiveObject` return, as in Python, the object's **best interface** (`GetBestInterface`): the default interface of its coclass (`IProvideClassInfo`), or the interface `IDispatch::GetTypeInfo` describes, built from its type library with `GetModule` (dual interfaces are called through the vtable). An object without type information becomes a dynamic object, or stays an `IUnknown` pointer when it has no `IDispatch`.
|
|
@@ -99,21 +158,21 @@ import { apartment, CreateObject, named, putProperty } from "@node-ctypes/comtyp
|
|
|
99
158
|
|
|
100
159
|
using _ = apartment();
|
|
101
160
|
|
|
102
|
-
using dict = CreateObject("Scripting.Dictionary"); // IDictionary, typed from scrrun.dll
|
|
161
|
+
using dict = await CreateObject("Scripting.Dictionary"); // IDictionary, typed from scrrun.dll
|
|
103
162
|
dict.CompareMode = 1; // property put (only while the dictionary is empty)
|
|
104
|
-
dict.Add("a", 1); // method
|
|
163
|
+
await dict.Add("a", 1); // method
|
|
105
164
|
console.log(dict.Count, dict.Item("a")); // property get, parameterized property
|
|
106
165
|
putProperty(dict, "Item", "a", 2); // parameterized property put (late bound, by name)
|
|
107
|
-
for (const key of dict) console.log(key); // _NewEnum / IEnumVARIANT
|
|
166
|
+
for (const key of dict) console.log(key); // _NewEnum / IEnumVARIANT; for await: on the executor
|
|
108
167
|
|
|
109
|
-
using fso = CreateObject("Scripting.FileSystemObject"); // IFileSystem3
|
|
110
|
-
using file = fso.CreateTextFile("C:\\Temp\\a.txt", named({ Overwrite: true })); // named arguments; ITextStream
|
|
168
|
+
using fso = await CreateObject("Scripting.FileSystemObject"); // IFileSystem3
|
|
169
|
+
using file = await fso.CreateTextFile("C:\\Temp\\a.txt", named({ Overwrite: true })); // named arguments; ITextStream
|
|
111
170
|
```
|
|
112
171
|
|
|
113
172
|
- **Static types**: the result is typed at run time, but its TypeScript type is `AutomationObject` (members of type `any`). For static types, create a coclass of a [generated module](#generated-modules).
|
|
114
173
|
- **Results**: `IDispatch` values returned by typed calls (a `VARIANT` holding an object, `Application.ActiveSheet`) get their best interface too (Python: `wrap_outparam`). `GetBestInterface(pointer)` (also `wrap`) does it explicitly and returns a new reference.
|
|
115
174
|
- **Iteration and helpers**: typed pointers deriving from `IDispatch` iterate their `_NewEnum` collection, and the late-bound helpers (`getProperty`, `putProperty`, `invokeMethod`, ...) accept them.
|
|
116
|
-
- **Options**: `{ interface: IFoo }` returns that interface; `{ dynamic: true }` a [dynamic object](#dynamic-objects); `CreateObject` also takes `clsctx` and `machine` (a remote computer, through `CoCreateInstanceEx`). `GetActiveObject(progid)` attaches to an object of the Running Object Table, `GetObject(displayName)` binds a moniker (`"winmgmts:"`, a file).
|
|
175
|
+
- **Options**: `{ interface: IFoo }` returns that interface; `{ dynamic: true }` a [dynamic object](#dynamic-objects); `{ home: true }` creates or binds it on the JavaScript thread ([Execution model](#execution-model)); `CreateObject` also takes `clsctx` and `machine` (a remote computer, through `CoCreateInstanceEx`). `GetActiveObject(progid)` attaches to an object of the Running Object Table, `GetObject(displayName)` binds a moniker (`"winmgmts:"`, a file).
|
|
117
176
|
|
|
118
177
|
### Constants
|
|
119
178
|
|
|
@@ -122,9 +181,9 @@ using file = fso.CreateTextFile("C:\\Temp\\a.txt", named({ Overwrite: true }));
|
|
|
122
181
|
```typescript
|
|
123
182
|
import { Constants, CreateObject } from "@node-ctypes/comtypes";
|
|
124
183
|
|
|
125
|
-
using fso = CreateObject("Scripting.FileSystemObject");
|
|
184
|
+
using fso = await CreateObject("Scripting.FileSystemObject");
|
|
126
185
|
const c = Constants(fso);
|
|
127
|
-
using temp = fso.GetSpecialFolder(c.TemporaryFolder); // or c.SpecialFolderConst.TemporaryFolder
|
|
186
|
+
using temp = await fso.GetSpecialFolder(c.TemporaryFolder); // or c.SpecialFolderConst.TemporaryFolder
|
|
128
187
|
```
|
|
129
188
|
|
|
130
189
|
### Dynamic objects
|
|
@@ -134,21 +193,21 @@ using temp = fso.GetSpecialFolder(c.TemporaryFolder); // or c.SpecialFolderConst
|
|
|
134
193
|
```typescript
|
|
135
194
|
import { CreateObject, GetObject } from "@node-ctypes/comtypes";
|
|
136
195
|
|
|
137
|
-
using wmi = GetObject("winmgmts:", { dynamic: true });
|
|
138
|
-
for (const os of wmi.ExecQuery("SELECT Caption FROM Win32_OperatingSystem")) console.log(os.Caption);
|
|
196
|
+
using wmi = await GetObject("winmgmts:", { dynamic: true });
|
|
197
|
+
for await (const os of await wmi.ExecQuery("SELECT Caption FROM Win32_OperatingSystem")) console.log(os.Caption);
|
|
139
198
|
|
|
140
|
-
using dict = CreateObject("Scripting.Dictionary", { dynamic: true });
|
|
141
|
-
dict.Add("a", 1);
|
|
142
|
-
console.log(dict("a")); // default member (DISPID_VALUE)
|
|
199
|
+
using dict = await CreateObject("Scripting.Dictionary", { dynamic: true });
|
|
200
|
+
await dict.Add("a", 1);
|
|
201
|
+
console.log(dict("a")); // default member (DISPID_VALUE), a property: synchronous
|
|
143
202
|
```
|
|
144
203
|
|
|
145
204
|
| Expression | Invoke |
|
|
146
205
|
| ------------------------------------------ | ------------------------------------------------------------------------ |
|
|
147
206
|
| `obj.Name` | `DISPATCH_PROPERTYGET`, or a method caller (see below) |
|
|
148
|
-
| `obj.Name(...args)` | `DISPATCH_METHOD \| DISPATCH_PROPERTYGET`
|
|
207
|
+
| `obj.Name(...args)` | `DISPATCH_METHOD \| DISPATCH_PROPERTYGET` (a `Promise` for methods) |
|
|
149
208
|
| `obj.Name = value` | `DISPATCH_PROPERTYPUT` (`PROPERTYPUTREF` for COM objects when supported) |
|
|
150
209
|
| `obj(...args)` | default member (`DISPID_VALUE`) |
|
|
151
|
-
| `for (const x of obj)`, `
|
|
210
|
+
| `for (const x of obj)`, `for await` | `_NewEnum` (`DISPID_NEWENUM`) and `IEnumVARIANT` |
|
|
152
211
|
| `getProperty(obj, name, ...args)` | `DISPATCH_PROPERTYGET` with arguments |
|
|
153
212
|
| `putProperty(obj, name, ...args, value)` | `DISPATCH_PROPERTYPUT` with arguments |
|
|
154
213
|
| `putRefProperty(...)`, `invokeMethod(...)` | `DISPATCH_PROPERTYPUTREF`, `DISPATCH_METHOD` only |
|
|
@@ -156,7 +215,7 @@ console.log(dict("a")); // default member (DISPID_VALUE)
|
|
|
156
215
|
Whether `obj.Name` reads a value or returns a callable comes from the type information (`IDispatch::GetTypeInfo`, cached per type):
|
|
157
216
|
|
|
158
217
|
- a property whose get has no required arguments is read: `dict.Count`, Excel `range.Value`;
|
|
159
|
-
- methods and properties with required arguments (`dict.Item`) return a function;
|
|
218
|
+
- methods and properties with required arguments (`dict.Item`) return a function: methods resolve a `Promise` (executor), parameterized properties return their value (synchronous);
|
|
160
219
|
- without type information (e.g. WMI objects), the property is read, and a function is returned only when the object rejects the get (`DISP_E_MEMBERNOTFOUND`, `DISP_E_BADPARAMCOUNT`, ...), as comtypes does.
|
|
161
220
|
|
|
162
221
|
A property whose get has only **optional** arguments is read as a value, so `shell.Environment("PROCESS")` would call the default member of the result: use `getProperty(shell, "Environment", "PROCESS")`.
|
|
@@ -167,7 +226,7 @@ Results that are objects are dynamic objects again, also inside arrays. Each dyn
|
|
|
167
226
|
|
|
168
227
|
- `undefined` is an omitted optional argument (`missing`: `VT_ERROR` with `DISP_E_PARAMNOTFOUND`).
|
|
169
228
|
- Named arguments go in a final `named({ Name: value })`.
|
|
170
|
-
- `byRef(value)` passes a variable by reference (VB `ByRef`) as `VT_BYREF | VT_VARIANT`, `byRef(value, VT_BSTR)` as `VT_BYREF | VT_BSTR`; its `value` holds what the callee left after the call (`const n = byRef(1); obj.Increment(n); n.value`).
|
|
229
|
+
- `byRef(value)` passes a variable by reference (VB `ByRef`) as `VT_BYREF | VT_VARIANT`, `byRef(value, VT_BSTR)` as `VT_BYREF | VT_BSTR`; its `value` holds what the callee left after the call (`const n = byRef(1); await obj.Increment(n); n.value`).
|
|
171
230
|
- `typed(vt, value)` and `safeArray(values, { vt, dimensions })` choose the VARIANT type.
|
|
172
231
|
|
|
173
232
|
### VARIANT conversions
|
|
@@ -288,7 +347,7 @@ export const IShellLinkWPart = COMInterface({
|
|
|
288
347
|
methods: [STDMETHOD(HRESULT, "GetPath", [c_void_p, c_int32, c_void_p, c_uint32]) /* ... */],
|
|
289
348
|
register: false, // do not replace the built-in definition for this IID
|
|
290
349
|
});
|
|
291
|
-
// link.GetPath(buffer, 260, null, 0): number
|
|
350
|
+
// link.GetPath(buffer, 260, null, 0): Promise<number>; sync(link).GetPath(...): number
|
|
292
351
|
```
|
|
293
352
|
|
|
294
353
|
Use `c_int32`/`c_uint32` for `LONG`/`DWORD`/`ULONG`: the `wintypes` aliases map the 32-bit `long` types to `bigint`. In-memory structures such as `GUID` can be passed to `POINTER(T)` parameters. `callMethod(name, ...args)` calls any slot by name. Definitions are registered by IID (the most recent wins) unless `register: false`.
|
|
@@ -336,10 +395,10 @@ class Counter extends COMObject {
|
|
|
336
395
|
|
|
337
396
|
const counter = new Counter();
|
|
338
397
|
using pointer = counter.QueryInterface(ICounter); // owned ICounter pointer (AddRef)
|
|
339
|
-
pointer.Increment(5);
|
|
398
|
+
await pointer.Increment(5); // called on the JavaScript thread: an apartment-threaded object
|
|
340
399
|
using dynamic = Dispatch(counter); // late binding through the generated IDispatch
|
|
341
|
-
using dict = CreateObject("Scripting.Dictionary");
|
|
342
|
-
dict.Add("counter", counter); // pass it to native code like any COM object
|
|
400
|
+
using dict = await CreateObject("Scripting.Dictionary");
|
|
401
|
+
await dict.Add("counter", counter); // pass it to native code like any COM object
|
|
343
402
|
```
|
|
344
403
|
|
|
345
404
|
- **Implementations** are found by vtable name (`Increment`, `_get_Label`, `_set_Label`); accessors fall back to a property of the same name. Missing implementations return `E_NOTIMPL`.
|
|
@@ -347,7 +406,7 @@ dict.Add("counter", counter); // pass it to native code like any COM object
|
|
|
347
406
|
- **Interface arguments** (pointers and dispatch objects) are lent for the duration of the call and released afterwards: `QueryInterface` or `AddRef` them to keep them.
|
|
348
407
|
- **Late binding** for interfaces deriving from `IDispatch`: the members of the declared interfaces (their `dispid`s, and their parameter names for named arguments) and the public JavaScript members (methods, accessors and fields, not `_`-prefixed); `_com_default_member_` answers `DISPID_VALUE`; iterable objects answer `_NewEnum` with a `VariantEnumerator`. Override `_invoke_` / `_ids_of_names_` to customize. Interfaces built from a type library (`GetModule`, generated modules) also provide their `ITypeInfo` through `GetTypeInfo`.
|
|
349
408
|
- **Lifetime**: native reference counting; while COM holds references the object is kept alive; `_final_release_()` runs when the count drops to zero. `getLiveObjectCount()` helps detect leaks.
|
|
350
|
-
- **Threading**: callbacks run on the JavaScript thread
|
|
409
|
+
- **Threading**: callbacks run on the JavaScript thread. With `_threading_ = "apartment"` (the default, for STA objects) calls on the object, and calls passing it as an argument, run on the JavaScript thread instead of the executor. `"free"` uses thread-safe callbacks: calls from the executor and other threads are queued to the JavaScript thread and wait for it, so they deadlock while that thread is blocked in a synchronous COM call that waits for them (`sync()`, a call at home).
|
|
351
410
|
|
|
352
411
|
### Errors in implementations
|
|
353
412
|
|
|
@@ -438,13 +497,15 @@ Registering the type library matters across processes. `IDispatch` is marshaled
|
|
|
438
497
|
```typescript
|
|
439
498
|
import { CreateObject, GetModule } from "@node-ctypes/comtypes";
|
|
440
499
|
|
|
441
|
-
const Scripting = GetModule("scrrun.dll") as any; // Python: comtypes.client.GetModule; untyped: generate a module for static types
|
|
442
|
-
using fso = CreateObject(Scripting.FileSystemObject); // the coclass default interface (IFileSystem3), through the vtable
|
|
443
|
-
using temp = fso.GetSpecialFolder(Scripting.SpecialFolderConst.TemporaryFolder); // IFolder
|
|
500
|
+
const Scripting = (await GetModule("scrrun.dll")) as any; // Python: comtypes.client.GetModule; untyped: generate a module for static types
|
|
501
|
+
using fso = await CreateObject(Scripting.FileSystemObject); // the coclass default interface (IFileSystem3), through the vtable
|
|
502
|
+
using temp = await fso.GetSpecialFolder(Scripting.SpecialFolderConst.TemporaryFolder); // IFolder
|
|
444
503
|
console.log(temp.Path);
|
|
445
504
|
```
|
|
446
505
|
|
|
447
|
-
`GetModule(source)` loads a type library and builds
|
|
506
|
+
`GetModule(source)` loads a type library and builds in memory every type: enums (frozen objects), records (`Structure` classes), interfaces (COMMETHOD, dual interfaces through the vtable), dispinterfaces (DISPMETHOD / DISPPROPERTY), coclasses (`CoClass`: `CreateObject(coclass)` returns the default interface), aliases and module constants. Interfaces defined by node-comtypes (`IUnknown`, `IDispatch`, `IEnumVARIANT`, ...) are reused; references between interfaces are resolved lazily. Results are cached per LIBID, version and LCID.
|
|
507
|
+
|
|
508
|
+
Reading and building a library is mostly JavaScript work on the calling thread (a large library such as mshtml takes a few seconds). `await GetModule()` does it in slices of a few milliseconds and yields to the event loop between them, so timers, I/O and an Electron UI keep running; concurrent calls for the same library share one build. `getModuleSync(source)` does the same work at once, for code that cannot wait (the cache is shared). `CreateObject`, `GetObject` and `GetActiveObject` load the type library of the object's best interface this way before returning it. The library of an object in another apartment or process is read from the same registered library loaded in-process, not call by call through its proxy.
|
|
448
509
|
|
|
449
510
|
Sources: a file (`"scrrun.dll"`, a path, `"file.dll\\2"`), a LIBID (`"{...}"` or `{ libid, major, minor, lcid }`, highest registered version by default), a ProgID (`"Scripting.Dictionary"`, through the registry, without creating the object) or an `ITypeLib` pointer. Lower level: `loadTypeLib`, `typeLibOf(object)`, `readTypeLib` (a JSON-serializable model) and `buildModule(model)`.
|
|
450
511
|
|
|
@@ -461,16 +522,17 @@ npx -p @node-ctypes/comtypes node-comtypes info scrrun.dll # without installing
|
|
|
461
522
|
import { CreateObject } from "@node-ctypes/comtypes";
|
|
462
523
|
import * as Scripting from "./com/Scripting.ts";
|
|
463
524
|
|
|
464
|
-
using dict = CreateObject(Scripting.Dictionary); // InterfacePointer<IDictionary>
|
|
525
|
+
using dict = await CreateObject(Scripting.Dictionary); // InterfacePointer<IDictionary>
|
|
465
526
|
dict.CompareMode = Scripting.CompareMethod.TextCompare;
|
|
466
527
|
const count: number = dict.Count; // read-only: assigning it is a type error
|
|
528
|
+
const exists: boolean = await dict.Exists("a"); // methods: Promise<...>; sync(dict).Exists("a"): boolean
|
|
467
529
|
```
|
|
468
530
|
|
|
469
531
|
A generated module embeds the library model and builds it with `buildModule` at import time (what `GetModule` does), and adds static types:
|
|
470
532
|
|
|
471
533
|
- enums as frozen objects with literal member types, and a union type of their values;
|
|
472
534
|
- record field interfaces;
|
|
473
|
-
- one `…Methods` interface per interface and dispinterface (methods, properties, read-only properties, `SELF` and cross references);
|
|
535
|
+
- one `…Methods` interface per interface and dispinterface (methods returning promises, properties, read-only properties, `SELF` and cross references), and `…SyncMethods` for `sync()` views;
|
|
474
536
|
- typed coclasses and constants.
|
|
475
537
|
|
|
476
538
|
Python's `comtypes.gen` cache corresponds to `GetModule(source, { cacheDir })` (or `NODE_COMTYPES_CACHE`), which also writes `<Library>.ts`. The generator is `generateModule(model)` / `writeModule(model, directory)`.
|
|
@@ -495,13 +557,14 @@ Visual Basic run-time errors (`FACILITY_CONTROL`, `0x800Axxxx`, e.g. from the Sc
|
|
|
495
557
|
- `COMInterface`, `COMMETHOD`, `STDMETHOD`, `DISPMETHOD`, `DISPPROPERTY` and the parameter types (`BSTR`, `LPOLESTR`, `REFGUID`, `SAFEARRAY`, `SELF`, `DATE`, `CURRENCY`, `lazy`, `dispid`, `helpstring`);
|
|
496
558
|
- `COMPointer`, `CoInitializeEx`, `apartment`, `CoCreateInstance(Ex)`, `CoGetClassObject`, `CLSCTX_*` / `COINIT_*`;
|
|
497
559
|
- message pump: `startMessagePump`, `waitFor`, `pumpMessages`, `PumpEvents`;
|
|
498
|
-
- threads: `marshalInterface`, `unmarshalInterface`, `unmarshalDispatch`, `releaseMarshaled`, `GlobalInterfaceTable
|
|
499
|
-
-
|
|
560
|
+
- threads: `marshalInterface`, `unmarshalInterface`, `unmarshalDispatch`, `releaseMarshaled`, `GlobalInterfaceTable`;
|
|
561
|
+
- execution: `sync`, `run`, `stats`, `finalize`.
|
|
562
|
+
- **`@node-ctypes/comtypes/client`**: `CreateObject`, `GetObject`, `sync`, `GetActiveObject`, `GetBestInterface` / `wrap`, `Constants`, `Dispatch` and the dynamic object helpers (`getProperty`, `putProperty`, `putRefProperty`, `invokeMethod`, `enumerate`, `dispatchPointer`, `isDispatch`, `release`, `memberInfo`, `typeName`), `GetEvents`, `ShowEvents`.
|
|
500
563
|
- **`@node-ctypes/comtypes/automation`**: `VARIANT`, `typed`, `safeArray`, `byRef` / `ByRef`, `named`, `missing`, `ErrorValue`, `record` / `RecordInfo`, SAFEARRAY functions, `DECIMAL`, dates, `DISPPARAMS`, `EXCEPINFO`, `invoke` / `getIDsOfNames`, `setDefaultLCID`, type information helpers, `VT_*` / `DISPID_*` and the other automation constants.
|
|
501
|
-
- **`@node-ctypes/comtypes/typelib`**: `GetModule`, `loadTypeLib` and the registered library functions, `typeLibOf`, `readTypeLib` and the model types, `buildModule`, `generateModule`, `writeModule`, `createTypeLib`, `registerTypeLib`, `unregisterTypeLib`, `isCoClass` / `CoClass`.
|
|
564
|
+
- **`@node-ctypes/comtypes/typelib`**: `GetModule`, `getModuleSync`, `loadTypeLib` and the registered library functions, `typeLibOf`, `readTypeLib` and the model types, `buildModule`, `generateModule`, `writeModule`, `createTypeLib`, `registerTypeLib`, `unregisterTypeLib`, `isCoClass` / `CoClass`.
|
|
502
565
|
- **`@node-ctypes/comtypes/server`**: `COMObject`, `VariantEnumerator`, `ConnectionPoint`, `ClassFactory`, `DispatchError`, `ReturnHRESULT`, `registerClassObject`, `registerServer`, `unregisterServer`, `runLocalServer`, `UseCommandLine`, `REGCLS_*`, `setErrorInfo`, `getLiveObjectCount`.
|
|
503
566
|
- **`@node-ctypes/comtypes/interfaces`**: the [built-in interfaces](#built-in-interfaces) with their structures and constants.
|
|
504
|
-
- **`@node-ctypes/comtypes/low-level`**: lazy `ole32`/`oleaut32` bindings, raw vtable access (`rawQueryInterface`, `rawAddRef`, `rawRelease`), BSTR and task-memory helpers, registry helpers.
|
|
567
|
+
- **`@node-ctypes/comtypes/low-level`**: lazy `ole32`/`oleaut32` bindings, `executorCall` (a raw call on the COM executor, with `IErrorInfo`), raw vtable access (`rawQueryInterface`, `rawAddRef`, `rawRelease`), BSTR and task-memory helpers, registry helpers.
|
|
505
568
|
|
|
506
569
|
## Python comtypes correspondence
|
|
507
570
|
|
|
@@ -526,7 +589,8 @@ Visual Basic run-time errors (`FACILITY_CONTROL`, `0x800Axxxx`, e.g. from the Sc
|
|
|
526
589
|
| `del p` / refcount | `p.Release()` / `using` |
|
|
527
590
|
| `COMError(hresult, text, details)` | `COMError` with `hresult`, `text`, `details` |
|
|
528
591
|
| **Client** | |
|
|
529
|
-
| `client.CreateObject(progid)` | `CreateObject(progid)` (best interface)
|
|
592
|
+
| `client.CreateObject(progid)` | `await CreateObject(progid)` (best interface) |
|
|
593
|
+
| `obj.Method(...)` (blocking) | `await obj.Method(...)`; blocking: `sync(obj).Method(...)` |
|
|
530
594
|
| `client.CreateObject(progid, dynamic=True)` | `CreateObject(progid, { dynamic: true })` |
|
|
531
595
|
| `client.GetActiveObject`, `client.GetObject` | `GetActiveObject`, `GetObject` |
|
|
532
596
|
| `client.GetBestInterface`, `client.wrap` | `GetBestInterface`, `wrap` |
|
|
@@ -541,7 +605,7 @@ Visual Basic run-time errors (`FACILITY_CONTROL`, `0x800Axxxx`, e.g. from the Sc
|
|
|
541
605
|
| `client.PumpEvents` | `PumpEvents` (+ `startMessagePump`) |
|
|
542
606
|
| `CoMarshalInterThreadInterfaceInStream`, GIT | `marshalInterface` / `unmarshalInterface`, `GlobalInterfaceTable` |
|
|
543
607
|
| **Type libraries** | |
|
|
544
|
-
| `client.GetModule(path)`, `comtypes.gen` | `GetModule(path, { cacheDir })`, `node-comtypes generate`
|
|
608
|
+
| `client.GetModule(path)`, `comtypes.gen` | `await GetModule(path, { cacheDir })`, `node-comtypes generate` |
|
|
545
609
|
| generated `CoClass` subclasses | `CoClass` objects; `CreateObject(coclass)` |
|
|
546
610
|
| `typeinfo.CreateTypeLib`, `RegisterTypeLib` | `createTypeLib`, `registerTypeLib`, `unregisterTypeLib` |
|
|
547
611
|
| **Servers** | |
|
|
@@ -560,7 +624,9 @@ Visual Basic run-time errors (`FACILITY_CONTROL`, `0x800Axxxx`, e.g. from the Sc
|
|
|
560
624
|
|
|
561
625
|
## Compatibility and limits
|
|
562
626
|
|
|
563
|
-
-
|
|
627
|
+
- Methods run on one executor thread, in order: a slow call delays the next ones (not the event loop). Each costs a round trip to that thread; see [Synchronous calls](#synchronous-calls) for chatty loops. Win32 messages are pumped only on request ([Message pump](#message-pump)).
|
|
628
|
+
- Objects inside `ByRef` arguments and `VARIANT` structures passed by address are not handed over between apartments: in a single-threaded home, pass such arguments to objects created with `{ home: true }` or use `sync()`.
|
|
629
|
+
- Hand-rolled vtables (`COMObject`s aside) that are not thread-safe must not be passed to methods of objects shared with the executor in a multithreaded home.
|
|
564
630
|
- Objects returned without `{ dynamic: true }` expose the members of their type library only: properties added at run time (WMI class properties, `IDispatchEx`) need a dynamic object, as in Python. An unknown member of a typed pointer is `undefined` (Python raises `AttributeError`), and typed pointers cannot be called for their default member.
|
|
565
631
|
- A dynamic property whose get has only optional arguments is read as a value ([Dynamic objects](#dynamic-objects)).
|
|
566
632
|
- `named()` works at run time only: static signatures are positional.
|
|
@@ -568,7 +634,7 @@ Visual Basic run-time errors (`FACILITY_CONTROL`, `0x800Axxxx`, e.g. from the Sc
|
|
|
568
634
|
- `VT_RECORD` needs a record type with a GUID in its type library (an `IRecordInfo` requirement).
|
|
569
635
|
- Custom vtable interfaces cross apartments and processes only with a registered type library or proxy/stub; `IDispatch` always does.
|
|
570
636
|
- In-process servers (InprocServer32) cannot host Node.js, so `_reg_threading_` and `_reg_clsctx_` have no equivalent; a native shim forwarding to a LocalServer is a possible future addition.
|
|
571
|
-
- `_threading_ = "free"` objects deadlock when called from another thread while the JavaScript thread is blocked in a synchronous COM call.
|
|
637
|
+
- `_threading_ = "free"` objects deadlock when called from another thread while the JavaScript thread is blocked in a synchronous COM call (`sync()` or a call at home) waiting for that call.
|
|
572
638
|
- The Scripting runtime and the Shell do not implement `ISupportErrorInfo`: their vtable failures have no `details`.
|
|
573
639
|
|
|
574
640
|
Implementation flows, in Italian: [FLOWS.md](./FLOWS.md).
|
|
@@ -594,6 +660,7 @@ Examples, after a build (`node examples/<name>.ts`):
|
|
|
594
660
|
- [server.ts](./examples/server.ts): a `COMObject` with events, used through the vtable, `IDispatch` and native code;
|
|
595
661
|
- [localserver.ts](./examples/localserver.ts): a LocalServer32 registered with `UseCommandLine`;
|
|
596
662
|
- [active-directory.ts](./examples/active-directory.ts): Active Directory search through ADSI `IDirectorySearch`, with the structures and enums of the Active DS type library;
|
|
663
|
+
- [active-directory-sync.ts](./examples/active-directory-sync.ts): the same search with every call synchronous on the JavaScript thread (`sync()`, `getModuleSync`, `CoGetObject`): faster, but it blocks the event loop for the whole search;
|
|
597
664
|
- [typelib.ts](./examples/typelib.ts): `GetModule` and coclasses.
|
|
598
665
|
|
|
599
666
|
## License
|
|
@@ -24,3 +24,9 @@ export interface InvokeOptions {
|
|
|
24
24
|
* are new owned pointers.
|
|
25
25
|
*/
|
|
26
26
|
export declare function invoke(dispatch: DispatchPointer, dispid: number, flags: number, args?: readonly unknown[], options?: InvokeOptions): unknown;
|
|
27
|
+
/**
|
|
28
|
+
* {@link invoke} on the COM executor: the VARIANTs are built and read on the
|
|
29
|
+
* JavaScript thread, `Invoke` runs on the executor (or on the home thread
|
|
30
|
+
* when the object or an argument must stay there).
|
|
31
|
+
*/
|
|
32
|
+
export declare function invokeAsync(dispatch: DispatchPointer, dispid: number, flags: number, args?: readonly unknown[], options?: InvokeOptions): Promise<unknown>;
|
|
@@ -6,6 +6,8 @@ import { POINTER_SIZE, takeBSTR } from "../low-level/native.js";
|
|
|
6
6
|
import { DISPATCH_PROPERTYPUT, DISPATCH_PROPERTYPUTREF, DISPID_PROPERTYPUT, LOCALE_NEUTRAL } from "./constants.js";
|
|
7
7
|
import { DISPPARAMS, EXCEPINFO } from "./types.js";
|
|
8
8
|
import { ByRef, VARIANT, VARIANT_SIZE, byRefArgument, clearVariant, missing, readVariant, writeVariant } from "./variant.js";
|
|
9
|
+
import { invokeSlotAsync, sync } from "../pointer.js";
|
|
10
|
+
import { linkOperation } from "../executor/operations.js";
|
|
9
11
|
/** Locale passed to `GetIDsOfNames` and `Invoke`; 0 as Python comtypes. */
|
|
10
12
|
export let defaultLCID = LOCALE_NEUTRAL;
|
|
11
13
|
export function setDefaultLCID(lcid) {
|
|
@@ -30,7 +32,7 @@ export function getIDsOfNames(dispatch, names, lcid = defaultLCID) {
|
|
|
30
32
|
const { pointers, keep } = wideStrings(names);
|
|
31
33
|
const dispids = Buffer.alloc(4 * names.length);
|
|
32
34
|
try {
|
|
33
|
-
dispatch.GetIDsOfNames(GUID_NULL, pointers, names.length, lcid, dispids);
|
|
35
|
+
sync(dispatch).GetIDsOfNames(GUID_NULL, pointers, names.length, lcid, dispids);
|
|
34
36
|
}
|
|
35
37
|
catch (error) {
|
|
36
38
|
if (error instanceof COMError && error.hresult === DISP_E_UNKNOWNNAME) {
|
|
@@ -53,14 +55,8 @@ function exceptionError(info, method, cause) {
|
|
|
53
55
|
const helpFile = takeBSTR(info.bstrHelpFile);
|
|
54
56
|
return new COMError(DISP_E_EXCEPTION, { method, details: { description, source, helpFile, helpContext: info.dwHelpContext, guid: null, scode: info.scode }, cause });
|
|
55
57
|
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
* (`undefined` is an omitted optional argument; `byRef(value)` is passed by
|
|
59
|
-
* reference and updated after the call); for property puts the last
|
|
60
|
-
* positional argument is the value. Returns the converted result; COM objects
|
|
61
|
-
* are new owned pointers.
|
|
62
|
-
*/
|
|
63
|
-
export function invoke(dispatch, dispid, flags, args = [], options = {}) {
|
|
58
|
+
// Converts the arguments; on failure, frees what was already converted.
|
|
59
|
+
function prepareInvoke(dispid, flags, args, options) {
|
|
64
60
|
const put = (flags & (DISPATCH_PROPERTYPUT | DISPATCH_PROPERTYPUTREF)) !== 0;
|
|
65
61
|
if (put && !args.length)
|
|
66
62
|
throw new TypeError("A property put requires a value");
|
|
@@ -86,6 +82,14 @@ export function invoke(dispatch, dispid, flags, args = [], options = {}) {
|
|
|
86
82
|
const info = new EXCEPINFO();
|
|
87
83
|
const argumentError = new ctypes.c_uint32();
|
|
88
84
|
const references = [];
|
|
85
|
+
const dispose = () => {
|
|
86
|
+
// ByRef arguments: read back what the callee left, then release it.
|
|
87
|
+
for (const reference of references)
|
|
88
|
+
reference.finish();
|
|
89
|
+
for (let index = 0; index < count; index++)
|
|
90
|
+
clearVariant(variants.subarray(index * VARIANT_SIZE, (index + 1) * VARIANT_SIZE));
|
|
91
|
+
result.clear();
|
|
92
|
+
};
|
|
89
93
|
try {
|
|
90
94
|
values.forEach((value, index) => {
|
|
91
95
|
const slot = variants.subarray(index * VARIANT_SIZE, (index + 1) * VARIANT_SIZE);
|
|
@@ -100,34 +104,79 @@ export function invoke(dispatch, dispid, flags, args = [], options = {}) {
|
|
|
100
104
|
throw new TypeError(`${method}: cannot convert argument ${position}: ${error.message}`, { cause: error });
|
|
101
105
|
}
|
|
102
106
|
});
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
dispose();
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
const params = new DISPPARAMS();
|
|
113
|
+
params.rgvarg = count ? ctypes.addressof(variants) : null;
|
|
114
|
+
params.rgdispidNamedArgs = namedDispids.length ? ctypes.addressof(dispids) : null;
|
|
115
|
+
params.cArgs = count;
|
|
116
|
+
params.cNamedArgs = namedDispids.length;
|
|
117
|
+
return {
|
|
118
|
+
args: [dispid, GUID_NULL, options.lcid ?? defaultLCID, flags, params, put ? null : result, info, ctypes.byref(argumentError)],
|
|
119
|
+
keep: [variants, dispids],
|
|
120
|
+
values,
|
|
121
|
+
result,
|
|
122
|
+
put,
|
|
123
|
+
translate(error) {
|
|
112
124
|
if (!(error instanceof COMError))
|
|
113
|
-
|
|
125
|
+
return error;
|
|
114
126
|
if (error.hresult === DISP_E_EXCEPTION)
|
|
115
|
-
|
|
127
|
+
return exceptionError(info, method, error);
|
|
116
128
|
if (error.hresult === DISP_E_TYPEMISMATCH || error.hresult === DISP_E_PARAMNOTFOUND) {
|
|
117
129
|
const index = argumentError.value;
|
|
118
130
|
const argumentIndex = index < namedValues.length ? index : count - 1 - index;
|
|
119
|
-
|
|
131
|
+
return new COMError(error.hresult, { method, details: { description: null, source: null, helpFile: null, helpContext: 0, guid: null, argumentIndex }, cause: error });
|
|
120
132
|
}
|
|
121
|
-
|
|
133
|
+
return new COMError(error.hresult, { method, details: error.details, cause: error });
|
|
134
|
+
},
|
|
135
|
+
dispose,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* `IDispatch::Invoke`. Positional arguments are converted to VARIANTs
|
|
140
|
+
* (`undefined` is an omitted optional argument; `byRef(value)` is passed by
|
|
141
|
+
* reference and updated after the call); for property puts the last
|
|
142
|
+
* positional argument is the value. Returns the converted result; COM objects
|
|
143
|
+
* are new owned pointers.
|
|
144
|
+
*/
|
|
145
|
+
export function invoke(dispatch, dispid, flags, args = [], options = {}) {
|
|
146
|
+
const prepared = prepareInvoke(dispid, flags, args, options);
|
|
147
|
+
try {
|
|
148
|
+
try {
|
|
149
|
+
sync(dispatch).Invoke(...prepared.args);
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
throw prepared.translate(error);
|
|
122
153
|
}
|
|
123
|
-
return readVariant(result._buffer);
|
|
154
|
+
return readVariant(prepared.result._buffer);
|
|
124
155
|
}
|
|
125
156
|
finally {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
157
|
+
prepared.dispose();
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* {@link invoke} on the COM executor: the VARIANTs are built and read on the
|
|
162
|
+
* JavaScript thread, `Invoke` runs on the executor (or on the home thread
|
|
163
|
+
* when the object or an argument must stay there).
|
|
164
|
+
*/
|
|
165
|
+
export function invokeAsync(dispatch, dispid, flags, args = [], options = {}) {
|
|
166
|
+
let prepared;
|
|
167
|
+
try {
|
|
168
|
+
prepared = prepareInvoke(dispid, flags, args, options);
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
return Promise.reject(error);
|
|
132
172
|
}
|
|
173
|
+
const slot = dispatch.interface.methodIndex.get("Invoke");
|
|
174
|
+
const results = prepared.put ? [] : [{ location: ctypes.addressof(prepared.result._buffer), kind: "variant" }];
|
|
175
|
+
const call = invokeSlotAsync(dispatch, slot, prepared.args, { inspect: prepared.values, results });
|
|
176
|
+
const converted = call
|
|
177
|
+
.then(() => readVariant(prepared.result._buffer), (error) => {
|
|
178
|
+
throw prepared.translate(error);
|
|
179
|
+
})
|
|
180
|
+
.finally(() => prepared.dispose());
|
|
181
|
+
return linkOperation(converted, call);
|
|
133
182
|
}
|
|
@@ -53,19 +53,19 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
|
|
|
53
53
|
import * as ctypes from "node-ctypes";
|
|
54
54
|
import { COMError } from "../errors.js";
|
|
55
55
|
import { ITypeInfo, ELEMDESC, FUNCDESC, TYPEATTR, VARDESC } from "../interfaces/typeinfo.js";
|
|
56
|
-
import { takeBSTR } from "../low-level/native.js";
|
|
57
|
-
import { COMPointer } from "../pointer.js";
|
|
56
|
+
import { copyStruct, takeBSTR } from "../low-level/native.js";
|
|
57
|
+
import { COMPointer, sync } from "../pointer.js";
|
|
58
58
|
import { INVOKE_FUNC, INVOKE_PROPERTYGET, INVOKE_PROPERTYPUT, INVOKE_PROPERTYPUTREF, MEMBERID_NIL, PARAMFLAG_FHASDEFAULT, PARAMFLAG_FLCID, PARAMFLAG_FOPT, PARAMFLAG_FRETVAL, VAR_DISPATCH } from "./constants.js";
|
|
59
59
|
import { defaultLCID } from "./dispatch.js";
|
|
60
60
|
/** `IDispatch::GetTypeInfo(0)`, or `null` when the object provides none. */
|
|
61
61
|
export function dispatchTypeInfo(dispatch, lcid = defaultLCID) {
|
|
62
62
|
try {
|
|
63
63
|
const count = new ctypes.c_uint32();
|
|
64
|
-
dispatch.GetTypeInfoCount(ctypes.byref(count));
|
|
64
|
+
sync(dispatch).GetTypeInfoCount(ctypes.byref(count));
|
|
65
65
|
if (!count.value)
|
|
66
66
|
return null;
|
|
67
67
|
const out = new ctypes.c_void_p();
|
|
68
|
-
dispatch.GetTypeInfo(0, lcid, ctypes.byref(out));
|
|
68
|
+
sync(dispatch).GetTypeInfo(0, lcid, ctypes.byref(out));
|
|
69
69
|
return out.value ? COMPointer.fromAddress(out.value, ITypeInfo) : null;
|
|
70
70
|
}
|
|
71
71
|
catch (error) {
|
|
@@ -77,47 +77,56 @@ export function dispatchTypeInfo(dispatch, lcid = defaultLCID) {
|
|
|
77
77
|
/** Run `use` with the TYPEATTR of `typeInfo`, released afterwards. */
|
|
78
78
|
export function withTypeAttr(typeInfo, use) {
|
|
79
79
|
const out = new ctypes.c_void_p();
|
|
80
|
-
typeInfo.GetTypeAttr(ctypes.byref(out));
|
|
80
|
+
sync(typeInfo).GetTypeAttr(ctypes.byref(out));
|
|
81
81
|
try {
|
|
82
|
-
return use(TYPEATTR
|
|
82
|
+
return use(copyStruct(TYPEATTR, out.value));
|
|
83
83
|
}
|
|
84
84
|
finally {
|
|
85
|
-
typeInfo.ReleaseTypeAttr(out.value);
|
|
85
|
+
sync(typeInfo).ReleaseTypeAttr(out.value);
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
88
|
export function withFuncDesc(typeInfo, index, use) {
|
|
89
89
|
const out = new ctypes.c_void_p();
|
|
90
|
-
typeInfo.GetFuncDesc(index, ctypes.byref(out));
|
|
90
|
+
sync(typeInfo).GetFuncDesc(index, ctypes.byref(out));
|
|
91
91
|
try {
|
|
92
|
-
return use(FUNCDESC
|
|
92
|
+
return use(copyStruct(FUNCDESC, out.value));
|
|
93
93
|
}
|
|
94
94
|
finally {
|
|
95
|
-
typeInfo.ReleaseFuncDesc(out.value);
|
|
95
|
+
sync(typeInfo).ReleaseFuncDesc(out.value);
|
|
96
96
|
}
|
|
97
97
|
}
|
|
98
98
|
export function withVarDesc(typeInfo, index, use) {
|
|
99
99
|
const out = new ctypes.c_void_p();
|
|
100
|
-
typeInfo.GetVarDesc(index, ctypes.byref(out));
|
|
100
|
+
sync(typeInfo).GetVarDesc(index, ctypes.byref(out));
|
|
101
101
|
try {
|
|
102
|
-
return use(VARDESC
|
|
102
|
+
return use(copyStruct(VARDESC, out.value));
|
|
103
103
|
}
|
|
104
104
|
finally {
|
|
105
|
-
typeInfo.ReleaseVarDesc(out.value);
|
|
105
|
+
sync(typeInfo).ReleaseVarDesc(out.value);
|
|
106
106
|
}
|
|
107
107
|
}
|
|
108
|
+
// Outputs of GetDocumentation, reused: the call is synchronous and cannot reenter.
|
|
109
|
+
const documentationName = new ctypes.c_void_p();
|
|
110
|
+
const documentationDoc = new ctypes.c_void_p();
|
|
111
|
+
const documentationContext = new ctypes.c_uint32();
|
|
112
|
+
const documentationFile = new ctypes.c_void_p();
|
|
113
|
+
const documentationNameRef = ctypes.byref(documentationName);
|
|
114
|
+
const documentationDocRef = ctypes.byref(documentationDoc);
|
|
115
|
+
const documentationContextRef = ctypes.byref(documentationContext);
|
|
116
|
+
const documentationFileRef = ctypes.byref(documentationFile);
|
|
108
117
|
/** `ITypeInfo::GetDocumentation`; `MEMBERID_NIL` documents the type itself. */
|
|
109
118
|
export function documentation(typeInfo, memid = MEMBERID_NIL) {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
typeInfo.GetDocumentation(memid,
|
|
115
|
-
return { name: takeBSTR(
|
|
119
|
+
documentationName.value = null;
|
|
120
|
+
documentationDoc.value = null;
|
|
121
|
+
documentationContext.value = 0;
|
|
122
|
+
documentationFile.value = null;
|
|
123
|
+
sync(typeInfo).GetDocumentation(memid, documentationNameRef, documentationDocRef, documentationContextRef, documentationFileRef);
|
|
124
|
+
return { name: takeBSTR(documentationName.value), docString: takeBSTR(documentationDoc.value), helpContext: documentationContext.value, helpFile: takeBSTR(documentationFile.value) };
|
|
116
125
|
}
|
|
117
126
|
/** Parameter flags of a FUNCDESC. */
|
|
118
127
|
export function parameterFlags(desc) {
|
|
119
128
|
const size = ctypes.sizeof(ELEMDESC);
|
|
120
|
-
return Array.from({ length: desc.cParams }, (_, index) => ELEMDESC
|
|
129
|
+
return Array.from({ length: desc.cParams }, (_, index) => copyStruct(ELEMDESC, desc.lprgelemdescParam + BigInt(index * size)).paramdesc.wParamFlags);
|
|
121
130
|
}
|
|
122
131
|
function collect(typeInfo, members, seen) {
|
|
123
132
|
const { key, functions, variables, implemented } = withTypeAttr(typeInfo, (attr) => ({ key: attr.guid.toString(), functions: attr.cFuncs, variables: attr.cVars, implemented: attr.cImplTypes }));
|
|
@@ -171,8 +180,8 @@ function collect(typeInfo, members, seen) {
|
|
|
171
180
|
const reference = new ctypes.c_uint32();
|
|
172
181
|
const base = new ctypes.c_void_p();
|
|
173
182
|
try {
|
|
174
|
-
typeInfo.GetRefTypeOfImplType(index, ctypes.byref(reference));
|
|
175
|
-
typeInfo.GetRefTypeInfo(reference.value, ctypes.byref(base));
|
|
183
|
+
sync(typeInfo).GetRefTypeOfImplType(index, ctypes.byref(reference));
|
|
184
|
+
sync(typeInfo).GetRefTypeInfo(reference.value, ctypes.byref(base));
|
|
176
185
|
}
|
|
177
186
|
catch {
|
|
178
187
|
continue;
|