forked from mhammond/pywin32
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonCOM.cpp
More file actions
2686 lines (2454 loc) · 113 KB
/
PythonCOM.cpp
File metadata and controls
2686 lines (2454 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// pythoncom.cpp :
/***
Note that this source file contains embedded documentation.
This documentation consists of marked up text inside the
C comments, and is prefixed with an '@' symbol. The source
files are processed by a tool called "autoduck" which
generates Windows .hlp files.
@doc
***/
#include "stdafx.h"
#include <objbase.h>
#include <ComSvcs.h>
#include "PythonCOM.h"
#include "PythonCOMServer.h"
#include "PyFactory.h"
#include "PyRecord.h"
#include "PyComTypeObjects.h"
#include "OleAcc.h" // for ObjectFromLresult proto...
#include "IAccess.h" // for IAccessControl
#include "pyerrors.h" // for PyErr_Warn in 2.5 and earlier...
extern int PyCom_RegisterCoreIIDs(PyObject *dict);
extern int PyCom_RegisterCoreSupport(void);
extern PyObject *pythoncom_IsGatewayRegistered(PyObject *self, PyObject *args);
extern PyObject *g_obPyCom_MapIIDToType;
extern PyObject *g_obPyCom_MapGatewayIIDToName;
extern PyObject *g_obPyCom_MapInterfaceNameToIID;
extern PyObject *g_obPyCom_MapRecordGUIDToRecordClass;
PyObject *g_obEmpty = NULL;
PyObject *g_obMissing = NULL;
PyObject *g_obArgNotFound = NULL;
PyObject *g_obNothing = NULL;
PyObject *PyCom_InternalError = NULL;
// Storage related functions.
extern PyObject *pythoncom_StgOpenStorage(PyObject *self, PyObject *args);
extern PyObject *pythoncom_StgOpenStorageEx(PyObject *self, PyObject *args, PyObject *kwargs);
extern PyObject *pythoncom_StgCreateStorageEx(PyObject *self, PyObject *args, PyObject *kwargs);
extern PyObject *pythoncom_FmtIdToPropStgName(PyObject *self, PyObject *args);
extern PyObject *pythoncom_PropStgNameToFmtId(PyObject *self, PyObject *args);
extern PyObject *pythoncom_StgIsStorageFile(PyObject *self, PyObject *args);
extern PyObject *pythoncom_StgCreateDocfile(PyObject *self, PyObject *args);
extern PyObject *pythoncom_StgCreateDocfileOnILockBytes(PyObject *self, PyObject *args);
extern PyObject *pythoncom_StgOpenStorageOnILockBytes(PyObject *self, PyObject *args);
extern PyObject *pythoncom_WriteClassStg(PyObject *self, PyObject *args);
extern PyObject *pythoncom_ReadClassStg(PyObject *self, PyObject *args);
extern PyObject *pythoncom_WriteClassStm(PyObject *self, PyObject *args);
extern PyObject *pythoncom_ReadClassStm(PyObject *self, PyObject *args);
extern PyObject *pythoncom_CreateStreamOnHGlobal(PyObject *self, PyObject *args);
extern PyObject *pythoncom_CreateILockBytesOnHGlobal(PyObject *self, PyObject *args);
extern PyObject *pythoncom_GetRecordFromGuids(PyObject *self, PyObject *args);
extern PyObject *pythoncom_GetRecordFromTypeInfo(PyObject *self, PyObject *args);
extern PyObject *Py_NewSTGMEDIUM(PyObject *self, PyObject *args);
// Typelib related functions
extern PyObject *pythoncom_loadtypelib(PyObject *self, PyObject *args);
extern PyObject *pythoncom_loadregtypelib(PyObject *self, PyObject *args);
extern PyObject *pythoncom_registertypelib(PyObject *self, PyObject *args);
extern PyObject *pythoncom_unregistertypelib(PyObject *self, PyObject *args);
extern PyObject *pythoncom_querypathofregtypelib(PyObject *self, PyObject *args);
// Type object helpers
PyObject *Py_NewFUNCDESC(PyObject *self, PyObject *args);
PyObject *Py_NewTYPEATTR(PyObject *self, PyObject *args);
PyObject *Py_NewVARDESC(PyObject *self, PyObject *args);
// Error related functions
void GetScodeString(SCODE sc, TCHAR *buf, int bufSize);
LPCTSTR GetScodeRangeString(SCODE sc);
LPCTSTR GetSeverityString(SCODE sc);
LPCTSTR GetFacilityString(SCODE sc);
/* Debug/Test helpers */
extern LONG _PyCom_GetInterfaceCount(void);
extern LONG _PyCom_GetGatewayCount(void);
// Function pointers we load at runtime.
#define CHECK_PFN(fname) \
if (pfn##fname == NULL) \
return PyCom_BuildPyException(E_NOTIMPL);
// Requires IE 5.5 or later
typedef HRESULT(STDAPICALLTYPE *CreateURLMonikerExfunc)(LPMONIKER, LPCWSTR, LPMONIKER *, DWORD);
static CreateURLMonikerExfunc pfnCreateURLMonikerEx = NULL;
// Win2k or later
typedef HRESULT(STDAPICALLTYPE *CoWaitForMultipleHandlesfunc)(DWORD dwFlags, DWORD dwTimeout, ULONG cHandles,
LPHANDLE pHandles, LPDWORD lpdwindex);
static CoWaitForMultipleHandlesfunc pfnCoWaitForMultipleHandles = NULL;
typedef HRESULT(STDAPICALLTYPE *CoGetObjectContextfunc)(REFIID, void **);
static CoGetObjectContextfunc pfnCoGetObjectContext = NULL;
typedef HRESULT(STDAPICALLTYPE *CoGetCancelObjectfunc)(DWORD, REFIID, void **);
static CoGetCancelObjectfunc pfnCoGetCancelObject = NULL;
typedef HRESULT(STDAPICALLTYPE *CoSetCancelObjectfunc)(IUnknown *);
static CoSetCancelObjectfunc pfnCoSetCancelObject = NULL;
// typedefs for the function pointers are in OleAcc.h
// WinXP or later
LPFNOBJECTFROMLRESULT pfnObjectFromLresult = NULL;
// May not be available on Windows 95, although I'm not sure that's even a concern anymore
typedef HRESULT(STDAPICALLTYPE *CoCreateInstanceExfunc)(REFCLSID, IUnknown *, DWORD, COSERVERINFO *, ULONG, MULTI_QI *);
static CoCreateInstanceExfunc pfnCoCreateInstanceEx = NULL;
typedef HRESULT(STDAPICALLTYPE *CoInitializeSecurityfunc)(PSECURITY_DESCRIPTOR, LONG, SOLE_AUTHENTICATION_SERVICE *,
void *, DWORD, DWORD, void *, DWORD, void *);
static CoInitializeSecurityfunc pfnCoInitializeSecurity = NULL;
BOOL PyCom_HasDCom()
{
static BOOL bHaveDCOM = -1;
if (bHaveDCOM == -1) {
HMODULE hMod = GetModuleHandle(_T("ole32.dll"));
if (hMod) {
FARPROC fp = GetProcAddress(hMod, "CoInitializeEx");
bHaveDCOM = (fp != NULL);
}
else
bHaveDCOM = FALSE; // not much we can do!
}
return bHaveDCOM;
}
#ifdef _MSC_VER
#pragma optimize("y", off)
#endif // _MSC_VER
// This optimisation seems to screw things in release builds...
/* MODULE FUNCTIONS: pythoncom */
// @pymethod <o PyIUnknown>|pythoncom|CoCreateInstance|Create a new instance of an OLE automation server.
static PyObject *pythoncom_CoCreateInstance(PyObject *self, PyObject *args)
{
PyObject *obCLSID;
PyObject *obUnk;
DWORD dwClsContext;
PyObject *obiid;
CLSID clsid;
IUnknown *punk;
CLSID iid;
if (!PyArg_ParseTuple(args, "OOiO:CoCreateInstance",
&obCLSID, // @pyparm <o PyIID>|clsid||Class identifier (CLSID) of the object
&obUnk, // @pyparm <o PyIUnknown>|unkOuter||The outer unknown, or None
&dwClsContext, // @pyparm int|context||The create context for the object, combination of
// pythoncom.CLSCTX_* flags
&obiid)) // @pyparm <o PyIID>|iid||The IID required from the object
return NULL;
if (!PyWinObject_AsIID(obCLSID, &clsid))
return NULL;
if (!PyWinObject_AsIID(obiid, &iid))
return NULL;
if (!PyCom_InterfaceFromPyInstanceOrObject(obUnk, IID_IUnknown, (void **)&punk, TRUE))
return NULL;
// Make the call.
IUnknown *result = NULL;
PY_INTERFACE_PRECALL;
SCODE sc = CoCreateInstance(clsid, punk, dwClsContext, iid, (void **)&result);
if (punk)
punk->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(sc))
return PyCom_BuildPyException(sc);
return PyCom_PyObjectFromIUnknown(result, iid);
}
#ifdef _MSC_VER
#pragma optimize("", on)
#endif // _MSC_VER
#ifdef _MSC_VER
#pragma optimize("", off)
#endif // _MSC_VER
// @pymethod <o PyIUnknown>|pythoncom|CoCreateInstanceEx|Create a new instance of an OLE automation server possibly on a
// remote machine.
static PyObject *pythoncom_CoCreateInstanceEx(PyObject *self, PyObject *args)
{
CHECK_PFN(CoCreateInstanceEx);
PyObject *obCLSID;
PyObject *obUnk;
PyObject *obCoServer;
DWORD dwClsContext;
PyObject *obrgiids;
CLSID clsid;
COSERVERINFO serverInfo = {0, NULL, NULL, 0};
COSERVERINFO *pServerInfo = NULL;
IID *iids = NULL;
MULTI_QI *mqi = NULL;
IUnknown *punk = NULL;
PyObject *result = NULL;
ULONG numIIDs = 0;
ULONG i;
if (!PyArg_ParseTuple(args, "OOiOO:CoCreateInstanceEx",
&obCLSID, // @pyparm <o PyIID>|clsid||Class identifier (CLSID) of the object
&obUnk, // @pyparm <o PyIUnknown>|unkOuter||The outer unknown, or None
&dwClsContext, // @pyparm int|context||The create context for the object, combination of
// pythoncom.CLSCTX_* flags
&obCoServer, // @pyparm (server, authino=None, reserved1=0,reserved2=0)|serverInfo||May be
// None, or describes the remote server to execute on.
&obrgiids)) // @pyparm [<o PyIID>, ...]|iids||A list of IIDs required from the object
return NULL;
if (!PyWinObject_AsIID(obCLSID, &clsid))
goto done;
if (obCoServer == Py_None)
pServerInfo = NULL;
else {
pServerInfo = &serverInfo;
PyObject *obName, *obAuth = Py_None;
if (!PyArg_ParseTuple(obCoServer, "O|Oii", &obName, &obAuth, &serverInfo.dwReserved1,
&serverInfo.dwReserved2)) {
PyErr_Clear();
PyErr_SetString(PyExc_TypeError, "The SERVERINFO is not in the correct format");
goto done;
}
if (obAuth != Py_None) {
PyErr_SetString(PyExc_TypeError, "authinfo in the SERVERINFO must be None");
goto done;
}
if (!PyWinObject_AsWCHAR(obName, &serverInfo.pwszName, FALSE))
goto done;
}
if (!PyCom_InterfaceFromPyInstanceOrObject(obUnk, IID_IUnknown, (void **)&punk, TRUE))
goto done;
if (!SeqToVector(obrgiids, &iids, &numIIDs, PyWinObject_AsIID))
goto done;
mqi = new MULTI_QI[numIIDs];
if (mqi == NULL) {
PyErr_SetString(PyExc_MemoryError, "Allocating MULTIQI array");
goto done;
}
for (i = 0; i < numIIDs; i++) {
mqi[i].pIID = iids + i;
mqi[i].pItf = NULL;
mqi[i].hr = 0;
}
{ // scoping
PY_INTERFACE_PRECALL;
HRESULT hr = (*pfnCoCreateInstanceEx)(clsid, punk, dwClsContext, pServerInfo, numIIDs, mqi);
PY_INTERFACE_POSTCALL;
if (FAILED(hr)) {
PyCom_BuildPyException(hr);
goto done;
}
} // end scoping
result = PyTuple_New(numIIDs);
if (result == NULL)
goto done;
for (i = 0; i < numIIDs; i++) {
PyObject *obNew;
if (mqi[i].hr == 0) {
obNew = PyCom_PyObjectFromIUnknown(mqi[i].pItf, *mqi[i].pIID, FALSE);
mqi[i].pItf = NULL;
if (!obNew) {
Py_DECREF(result);
result = NULL;
goto done;
}
}
else {
obNew = Py_None;
Py_INCREF(Py_None);
}
PyTuple_SET_ITEM(result, i, obNew);
}
done:
PYCOM_RELEASE(punk);
if (serverInfo.pwszName)
PyWinObject_FreeWCHAR(serverInfo.pwszName);
for (i = 0; i < numIIDs; i++) PYCOM_RELEASE(mqi[i].pItf)
CoTaskMemFree(iids);
delete[] mqi;
return result;
}
#ifdef _MSC_VER
#pragma optimize("", on)
#endif // _MSC_VER
// @pymethod |pythoncom|CoInitializeSecurity|Registers security and sets the default security values.
static PyObject *pythoncom_CoInitializeSecurity(PyObject *self, PyObject *args)
{
CHECK_PFN(CoInitializeSecurity);
DWORD cAuthSvc;
SOLE_AUTHENTICATION_SERVICE *pAS = NULL;
DWORD dwAuthnLevel;
DWORD dwImpLevel;
DWORD dwCapabilities;
PSECURITY_DESCRIPTOR pSD = NULL, pSD_absolute = NULL;
IID appid;
IAccessControl *pIAC = NULL;
PyObject *obSD, *obAuthSvc, *obReserved1, *obReserved2, *obAuthInfo;
if (!PyArg_ParseTuple(
args, "OOOiiOiO:CoInitializeSecurity",
&obSD, // @pyparm <o PySECURITY_DESCRIPTOR>|sd||Security descriptor containing access permissions for
// process' objects, can be None. <nl>If Capabilities contains EOAC_APPID, sd should be an AppId
// (guid), or None to use server executable. <nl>If Capabilities contains EOAC_ACCESS_CONTROL, sd
// parameter should be an IAccessControl interface.
&obAuthSvc, // @pyparm object|authSvc||A value of None tells COM to choose which authentication services to
// use. An empty list means use no services.
&obReserved1, // @pyparm object|reserved1||Must be None
&dwAuthnLevel, // @pyparm int|authnLevel||One of pythoncom.RPC_C_AUTHN_LEVEL_* values. The default
// authentication level for proxies. On the server side, COM will fail calls that arrive at
// a lower level. All calls to AddRef and Release are made at this level.
&dwImpLevel, // @pyparm int|impLevel||One of pythoncom.RPC_C_IMP_LEVEL_* values. The default impersonation
// level for proxies. This value is not checked on the server side. AddRef and Release calls
// are made with this impersonation level so even security aware apps should set this
// carefully. Setting IUnknown security only affects calls to QueryInterface, not AddRef or
// Release.
&obAuthInfo, // @pyparm object|authInfo||Must be None
&dwCapabilities, // @pyparm int|capabilities||Authentication capabilities, combination of pythoncom.EOAC_*
// flags.
&obReserved2)) // @pyparm object|reserved2||Must be None
return NULL;
if (obReserved1 != Py_None || obReserved2 != Py_None || obAuthInfo != Py_None) {
PyErr_SetString(PyExc_TypeError, "Not all of the 'None' arguments are None!");
return NULL;
}
if (obAuthSvc == Py_None)
cAuthSvc = (DWORD)-1;
else if (PySequence_Check(obAuthSvc)) {
cAuthSvc = 0;
}
else {
PyErr_SetString(PyExc_TypeError, "obAuthSvc must be None or an empty sequence.");
return NULL;
}
// Depending on capabilities flags, first arg can be one of:
// AppId (or NULL to lookup server executable in APPID registry key)
// IAccessControl interface (cannot be NULL)
// Absolute security descriptor (or NULL to use a default SD)
if (dwCapabilities & EOAC_APPID) {
if (obSD != Py_None) {
if (!PyWinObject_AsIID(obSD, &appid))
return NULL;
pSD = (PSECURITY_DESCRIPTOR)&appid;
}
}
else if (dwCapabilities & EOAC_ACCESS_CONTROL) {
if (!PyCom_InterfaceFromPyObject(obSD, IID_IAccessControl, (void **)&pIAC, FALSE))
return NULL;
pSD = (PSECURITY_DESCRIPTOR)pIAC;
}
else {
if (!PyWinObject_AsSECURITY_DESCRIPTOR(obSD, &pSD, /*BOOL bNoneOK = */ TRUE))
return NULL;
// Security descriptor must be in absolute form
if (pSD) {
if (!_MakeAbsoluteSD(pSD, &pSD_absolute))
return NULL;
pSD = pSD_absolute;
}
}
PY_INTERFACE_PRECALL;
HRESULT hr =
(*pfnCoInitializeSecurity)(pSD, cAuthSvc, pAS, NULL, dwAuthnLevel, dwImpLevel, NULL, dwCapabilities, NULL);
if (pIAC)
pIAC->Release();
PY_INTERFACE_POSTCALL;
if (pSD_absolute != NULL)
FreeAbsoluteSD(pSD_absolute);
if (FAILED(hr))
return PyCom_BuildPyException(hr);
Py_INCREF(Py_None);
return Py_None;
}
#ifdef _MSC_VER
#pragma optimize("y", off)
#endif // _MSC_VER
// @pymethod int|pythoncom|CoRegisterClassObject|Registers an EXE class object with OLE so other applications can
// connect to it.
static PyObject *pythoncom_CoRegisterClassObject(PyObject *self, PyObject *args)
{
DWORD reg;
DWORD context;
DWORD flags;
PyObject *obIID, *obFactory;
IID iid;
if (!PyArg_ParseTuple(
args, "OOii:CoRegisterClassObject",
&obIID, // @pyparm <o PyIID>|iid||The IID of the object to register
&obFactory, // @pyparm <o PyIUnknown>|factory||The class factory object. It is the Python programmers
// responsibility to ensure this object remains alive until the class is unregistered.
&context, // @pyparm int|context||The create context for the server. Must be a combination of the CLSCTX_*
// flags.
&flags)) // @pyparm int|flags||Create flags.
return NULL;
// @comm The class factory object should be <o PyIClassFactory> object, but as per the COM documentation, only <o
// PyIUnknown> is checked.
if (!PyWinObject_AsIID(obIID, &iid))
return NULL;
IUnknown *pFactory;
if (!PyCom_InterfaceFromPyObject(obFactory, IID_IUnknown, (void **)&pFactory, /*BOOL bNoneOK=*/FALSE))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = CoRegisterClassObject(iid, pFactory, context, flags, ®);
pFactory->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
// @rdesc The result is a handle which should be revoked using <om pythoncom.CoRevokeClassObject>
return PyLong_FromLong(reg);
}
// @pymethod |pythoncom|CoRevokeClassObject|Informs OLE that a class object, previously registered with the <om
// pythoncom.CoRegisterClassObject> method, is no longer available for use.
static PyObject *pythoncom_CoRevokeClassObject(PyObject *self, PyObject *args)
{
DWORD reg;
if (!PyArg_ParseTuple(args, "i:CoRevokeClassObject",
®)) // @pyparm int|reg||The value returned from <om pythoncom.CoRegisterClassObject>
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = CoRevokeClassObject(reg);
PY_INTERFACE_POSTCALL;
if (FAILED(hr)) {
return PyCom_BuildPyException(hr);
}
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |pythoncom|CoResumeClassObjects|Called by a server that can register multiple class objects to inform the
// OLE SCM about all registered classes, and permits activation requests for those class objects.
static PyObject *pythoncom_CoResumeClassObjects(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":CoResumeClassObjects"))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = CoResumeClassObjects();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |pythoncom|CoTreatAsClass|Establishes or removes an emulation, in which objects of one class are treated as
// objects of a different class.
static PyObject *pythoncom_CoTreatAsClass(PyObject *self, PyObject *args)
{
PyObject *obguid1, *obguid2 = NULL;
if (!PyArg_ParseTuple(args, "O|O", &obguid1, &obguid2))
return NULL;
CLSID clsid1, clsid2 = GUID_NULL;
// @pyparm <o PyIID>|clsidold||CLSID of the object to be emulated.
// @pyparm <o PyIID>|clsidnew|CLSID_NULL|CLSID of the object that should emulate the original object. This replaces
// any existing emulation for clsidOld. Can be ommitted or CLSID_NULL, in which case any existing emulation for
// clsidOld is removed.
if (!PyWinObject_AsIID(obguid1, &clsid1))
return NULL;
if (obguid2 != NULL && !PyWinObject_AsIID(obguid2, &clsid2))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = CoTreatAsClass(clsid1, clsid2);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod <o PyIClassFactory>|pythoncom|MakePyFactory|Creates a new <o PyIClassFactory> object wrapping a PythonCOM
// Class Factory object.
static PyObject *pythoncom_MakePyFactory(PyObject *self, PyObject *args)
{
PyObject *obIID;
if (!PyArg_ParseTuple(args, "O:MakePyFactory",
&obIID)) // @pyparm <o PyIID>|iid||The IID of the object the class factory provides.
return NULL;
IID iid;
if (!PyWinObject_AsIID(obIID, &iid))
return NULL;
PY_INTERFACE_PRECALL;
CPyFactory *pFact = new CPyFactory(iid);
PY_INTERFACE_POSTCALL;
if (pFact == NULL)
return PyCom_BuildPyException(E_OUTOFMEMORY);
return PyCom_PyObjectFromIUnknown(pFact, IID_IClassFactory, /*bAddRef =*/FALSE);
}
// @pymethod int|pythoncom|_GetInterfaceCount|Retrieves the number of interface objects currently in existance
static PyObject *pythoncom_GetInterfaceCount(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":_GetInterfaceCount"))
return NULL;
return PyLong_FromLong(_PyCom_GetInterfaceCount());
// @comm If is occasionally a good idea to call this function before your Python program
// terminates. If this function returns non-zero, then you still have PythonCOM objects
// alive in your program (possibly in global variables).
}
// @pymethod int|pythoncom|_GetGatewayCount|Retrieves the number of gateway objects currently in existance
static PyObject *pythoncom_GetGatewayCount(PyObject *self, PyObject *args)
{
// @comm This is the number of Python object that implement COM servers which
// are still alive (ie, serving a client). The only way to reduce this count
// is to have the process which uses these PythonCOM servers release its references.
if (!PyArg_ParseTuple(args, ":_GetGatewayCount"))
return NULL;
return PyLong_FromLong(_PyCom_GetGatewayCount());
}
// @pymethod <o PyIUnknown>|pythoncom|GetActiveObject|Retrieves an object representing a running object registered with
// OLE
static PyObject *pythoncom_GetActiveObject(PyObject *self, PyObject *args)
{
PyObject *obCLSID;
// @pyparm CLSID|cls||The IID for the program. As for all CLSID's in Python, a "program.name" or IID format string
// may be used, or a real <o PyIID> object.
if (!PyArg_ParseTuple(args, "O:GetActiveObject", &obCLSID))
return NULL;
CLSID clsid;
if (!PyWinObject_AsIID(obCLSID, &clsid))
return NULL;
// Make the call.
IUnknown *result = NULL;
PY_INTERFACE_PRECALL;
SCODE sc = GetActiveObject(clsid, NULL, &result);
PY_INTERFACE_POSTCALL;
if (FAILED(sc))
return PyCom_BuildPyException(sc);
return PyCom_PyObjectFromIUnknown(result, IID_IUnknown);
}
// @pymethod <o PyIDispatch>|pythoncom|Connect|Connect to an already running OLE automation server.
static PyObject *pythoncom_connect(PyObject *self, PyObject *args)
{
PyObject *obCLSID;
// @pyparm CLSID|cls||An identifier for the program. Usually "program.item"
if (!PyArg_ParseTuple(args, "O:Connect", &obCLSID))
return NULL;
CLSID clsid;
if (!PyWinObject_AsIID(obCLSID, &clsid))
return NULL;
IUnknown *unk = NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = GetActiveObject(clsid, NULL, &unk);
PY_INTERFACE_POSTCALL;
if (FAILED(hr) || unk == NULL)
return PyCom_BuildPyException(hr);
IDispatch *disp = NULL;
SCODE sc;
// local scope for macro PY_INTERFACE_PRECALL local variables
{
PY_INTERFACE_PRECALL;
sc = unk->QueryInterface(IID_IDispatch, (void **)&disp);
unk->Release();
PY_INTERFACE_POSTCALL;
}
if (FAILED(sc) || disp == NULL)
return PyCom_BuildPyException(sc);
return PyCom_PyObjectFromIUnknown(disp, IID_IDispatch);
// @comm This function is equivalent to <om pythoncom.GetActiveObject>(clsid).<om
// pythoncom.QueryInterace>(pythoncom.IID_IDispatch)
}
// @pymethod <o PyIDispatch>|pythoncom|new|Create a new instance of an OLE automation server.
static PyObject *pythoncom_new(PyObject *self, PyObject *args)
{
PyErr_Clear();
PyObject *progid;
// @pyparm CLSID|cls||An identifier for the program. Usually "program.item"
if (!PyArg_ParseTuple(args, "O", &progid))
return NULL;
// @comm This is just a wrapper for the CoCreateInstance method.
// Specifically, this call is identical to:
// <nl>pythoncom.CoCreateInstance(cls, None, pythoncom.CLSCTX_SERVER, pythoncom.IID_IDispatch)
int clsctx = PyCom_HasDCom() ? CLSCTX_SERVER : CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER;
PyObject *obIID = PyWinObject_FromIID(IID_IDispatch);
PyObject *newArgs = Py_BuildValue("OOiO", progid, Py_None, clsctx, obIID);
Py_DECREF(obIID);
PyObject *rc = pythoncom_CoCreateInstance(self, newArgs);
Py_DECREF(newArgs);
return rc;
}
// @pymethod <o PyIID>|pythoncom|CreateGuid|Creates a new, unique GUIID.
static PyObject *pythoncom_createguid(PyObject *self, PyObject *args)
{
PyErr_Clear();
if (PyTuple_Size(args) != 0) {
PyErr_SetString(PyExc_TypeError, "function requires no arguments");
return NULL;
}
GUID guid;
PY_INTERFACE_PRECALL;
CoCreateGuid(&guid);
PY_INTERFACE_POSTCALL;
// @comm Use the CreateGuid function when you need an absolutely unique number that you will use as a persistent
// identifier in a distributed environment.To a very high degree of certainty, this function returns a unique value
// - no other invocation, on the same or any other system (networked or not), should return the same value.
return PyWinObject_FromIID(guid);
}
// @pymethod string|pythoncom|ProgIDFromCLSID|Converts a CLSID to a progID.
static PyObject *pythoncom_progidfromclsid(PyObject *self, PyObject *args)
{
PyObject *obCLSID;
// @pyparm IID|clsid||A CLSID (either in a string, or in an <o PyIID> object)
if (!PyArg_ParseTuple(args, "O", &obCLSID))
return NULL;
CLSID clsid;
if (!PyWinObject_AsIID(obCLSID, &clsid))
return NULL;
LPOLESTR progid = NULL;
PY_INTERFACE_PRECALL;
HRESULT sc = ProgIDFromCLSID(clsid, &progid);
PY_INTERFACE_POSTCALL;
if (FAILED(sc))
return PyCom_BuildPyException(sc);
PyObject *ob = MakeOLECHARToObj(progid);
CoTaskMemFree(progid);
return ob;
}
// @pymethod string|pythoncom|GetScodeString|Returns the string for an OLE scode (HRESULT)
static PyObject *pythoncom_GetScodeString(PyObject *self, PyObject *args)
{
SCODE scode;
TCHAR buf[512];
// @pyparm int|scode||The OLE error code for the scode string requested.
if (!PyArg_ParseTuple(args, "k", &scode))
return NULL;
GetScodeString(scode, buf, sizeof(buf) / sizeof(buf[0]));
return PyWinObject_FromTCHAR(buf);
// @comm This will obtain the COM Error message for a given HRESULT.
// Internally, PythonCOM uses this function to obtain the description
// when a <o com_error> COM Exception is raised.
}
// @pymethod string|pythoncom|GetScodeRangeString|Returns the scode range string, given an OLE scode.
static PyObject *pythoncom_GetScodeRangeString(PyObject *self, PyObject *args)
{
SCODE scode;
// @pyparm int|scode||An OLE error code to return the scode range string for.
if (!PyArg_ParseTuple(args, "k", &scode))
return NULL;
return PyWinObject_FromTCHAR(GetScodeRangeString(scode));
}
// @pymethod string|pythoncom|GetSeverityString|Returns the severity string, given an OLE scode.
static PyObject *pythoncom_GetSeverityString(PyObject *self, PyObject *args)
{
SCODE scode;
// @pyparm int|scode||The OLE error code for the severity string requested.
if (!PyArg_ParseTuple(args, "k", &scode))
return NULL;
return PyWinObject_FromTCHAR(GetSeverityString(scode));
}
// @pymethod string|pythoncom|GetFacilityString|Returns the facility string, given an OLE scode.
static PyObject *pythoncom_GetFacilityString(PyObject *self, PyObject *args)
{
SCODE scode;
// @pyparm int|scode||The OLE error code for the facility string requested.
if (!PyArg_ParseTuple(args, "k", &scode))
return NULL;
return PyWinObject_FromTCHAR(GetFacilityString(scode));
}
// @pymethod <o PyIDispatch>|pythoncom|UnwrapObject|Unwraps a Python instance in a gateway object.
static PyObject *pythoncom_UnwrapObject(PyObject *self, PyObject *args)
{
PyObject *ob;
// @pyparm <o PyIUnknown>|ob||The object to unwrap.
if (!PyArg_ParseTuple(args, "O", &ob))
return NULL;
// @comm If the object is not a PythonCOM object, then ValueError is raised.
if (!PyIBase::is_object(ob, &PyIUnknown::type)) {
PyErr_SetString(PyExc_ValueError, "argument is not a COM object");
return NULL;
}
// Unwrapper does not need thread state management
// Ie PY_INTERFACE_PRE/POSTCALL;
HRESULT hr;
IInternalUnwrapPythonObject *pUnwrapper;
if (S_OK !=
(hr = ((PyIUnknown *)ob)->m_obj->QueryInterface(IID_IInternalUnwrapPythonObject, (void **)&pUnwrapper))) {
PyErr_Format(PyExc_ValueError, "argument is not a Python gateway (0x%x)", hr);
return NULL;
}
PyObject *retval;
pUnwrapper->Unwrap(&retval);
pUnwrapper->Release();
if (S_OK != hr)
return PyCom_BuildPyException(hr);
return retval;
// Use this function to obtain the inverse of the <om WrapObject> method.
// Eg, if you pass to this function the value you received from <om WrapObject>, it
// will return the object you originally passed as the parameter to <om WrapObject>
}
// @pymethod <o PyIUnknown>|pythoncom|WrapObject|Wraps a Python instance in a gateway object.
static PyObject *pythoncom_WrapObject(PyObject *self, PyObject *args)
{
PyObject *ob;
PyObject *obIID = NULL;
IID iid = IID_IDispatch;
PyObject *obIIDInterface = NULL;
IID iidInterface = IID_IDispatch;
// @pyparm object|ob||The object to wrap.
// @pyparm <o PyIID>|gatewayIID|IID_IDispatch|The IID of the gateway object to create (ie, the interface of the
// server object wrapped by the return value)
// @pyparm <o PyIID>|interfaceIID|IID_IDispatch|The IID of the interface object to create (ie, the interface of the
// returned object)
if (!PyArg_ParseTuple(args, "O|OO", &ob, &obIID, &obIIDInterface))
return NULL;
// @rdesc Note that there are 2 objects created by this call - a gateway (server) object, suitable for
// use by other external COM clients/hosts, as well as the returned Python interface (client) object, which
// maps to the new gateway.
// <nl>There are some unusual cases where the 2 IID parameters will not be identical.
// If you need to do this, you should know exactly what you are doing, and why!
if (obIID && obIID != Py_None) {
if (!PyWinObject_AsIID(obIID, &iid))
return NULL;
}
if (obIIDInterface && obIIDInterface != Py_None) {
if (!PyWinObject_AsIID(obIIDInterface, &iidInterface))
return NULL;
}
// Make a gateway of the specific IID we ask for.
// The gateway must exist (ie, we _must_ support PyGIXXX
// XXX - do we need an optional arg for "base object"?
// XXX - If we did, we would unwrap it like this:
/****
IUnknown *pLook = (IUnknown *)(*ppv);
IInternalUnwrapPythonObject *pTemp;
if (pLook->QueryInterface(IID_IInternalUnwrapPythonObject, (void **)&pTemp)==S_OK) {
// One of our objects, so set the base object if it doesn't already have one
PyGatewayBase *pG = (PyGatewayBase *)pTemp;
// Eeek - just these few next lines need to be thread-safe :-(
PyWin_AcquireGlobalLock();
if (pG->m_pBaseObject==NULL && pG != (PyGatewayBase *)this) {
pG->m_pBaseObject = this;
pG->m_pBaseObject->AddRef();
}
PyWin_ReleaseGlobalLock();
pTemp->Release();
}
******/
IUnknown *pDispatch;
PY_INTERFACE_PRECALL;
HRESULT hr = PyCom_MakeRegisteredGatewayObject(iid, ob, NULL, (void **)&pDispatch);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
/* return a PyObject wrapping it */
return PyCom_PyObjectFromIUnknown(pDispatch, iidInterface, FALSE);
}
static PyObject *pythoncom_MakeIID(PyObject *self, PyObject *args)
{
PyErr_Warn(PyExc_DeprecationWarning, "MakeIID is deprecated - please use pywintypes.IID() instead.");
return PyWinMethod_NewIID(self, args);
}
// no autoduck - this is deprecated.
static PyObject *pythoncom_MakeTime(PyObject *self, PyObject *args)
{
PyErr_Warn(PyExc_DeprecationWarning, "MakeTime is deprecated - please use pywintypes.Time() instead.");
return PyWinMethod_NewTime(self, args);
}
// @pymethod <o PyIMoniker>,int,<o PyIBindCtx>|pythoncom|MkParseDisplayName|Parses a moniker display name into a moniker
// object. The inverse of <om PyIMoniker.GetDisplayName>
static PyObject *pythoncom_MkParseDisplayName(PyObject *self, PyObject *args)
{
WCHAR *displayName = NULL;
PyObject *obDisplayName;
PyObject *obBindCtx = NULL;
// @pyparm string|displayName||The display name to parse
// @pyparm <o PyIBindCtx>|bindCtx|None|The bind context object to use.
// @comm If a binding context is not provided, then one will be created.
// Any binding context created or passed in will be returned to the
// caller.
if (!PyArg_ParseTuple(args, "O|O:MkParseDisplayName", &obDisplayName, &obBindCtx))
return NULL;
if (!PyWinObject_AsWCHAR(obDisplayName, &displayName, FALSE))
return NULL;
HRESULT hr;
IBindCtx *pBC;
if (obBindCtx == NULL || obBindCtx == Py_None) {
hr = CreateBindCtx(0, &pBC);
if (FAILED(hr)) {
PyWinObject_FreeWCHAR(displayName);
return PyCom_BuildPyException(hr);
}
/* pass the pBC ref into obBindCtx */
if (!(obBindCtx = PyCom_PyObjectFromIUnknown(pBC, IID_IBindCtx, FALSE))) {
PyWinObject_FreeWCHAR(displayName);
return NULL;
}
}
else {
if (!PyCom_InterfaceFromPyObject(obBindCtx, IID_IBindCtx, (LPVOID *)&pBC, FALSE)) {
PyWinObject_FreeWCHAR(displayName);
return NULL;
}
/* we want our own ref to obBindCtx, but not pBC */
Py_INCREF(obBindCtx);
pBC->Release();
}
/* at this point: we own a ref to obBindCtx, but not a direct one on pBC
(obBindCtx itself has an indirect reference to pBC though, so it is still
safe to use ...)
*/
ULONG chEaten;
IMoniker *pmk;
PY_INTERFACE_PRECALL;
hr = MkParseDisplayName(pBC, displayName, &chEaten, &pmk);
PY_INTERFACE_POSTCALL;
PyWinObject_FreeWCHAR(displayName);
if (FAILED(hr)) {
Py_DECREF(obBindCtx);
return PyCom_BuildPyException(hr);
}
/* build the result */
return Py_BuildValue("NiN", PyCom_PyObjectFromIUnknown(pmk, IID_IMoniker, FALSE), chEaten, obBindCtx);
}
// @pymethod <o PyIMoniker>|pythoncom|CreatePointerMoniker|Creates a new <o PyIMoniker> object.
static PyObject *pythoncom_CreatePointerMoniker(PyObject *self, PyObject *args)
{
PyObject *obUnk;
// @pyparm <o PyIUnknown>|IUnknown||The interface for the moniker.
if (!PyArg_ParseTuple(args, "O:CreatePointerMoniker", &obUnk))
return NULL;
IUnknown *punk;
if (!PyCom_InterfaceFromPyObject(obUnk, IID_IUnknown, (LPVOID *)&punk, FALSE))
return NULL;
IMoniker *pmk;
PY_INTERFACE_PRECALL;
HRESULT hr = CreatePointerMoniker(punk, &pmk);
punk->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pmk, IID_IMoniker, FALSE);
}
// @pymethod <o PyIMoniker>|pythoncom|CreateFileMoniker|Creates a new <o PyIMoniker> object.
static PyObject *pythoncom_CreateFileMoniker(PyObject *self, PyObject *args)
{
PyObject *obName;
// @pyparm string|filename||The name of the file.
if (!PyArg_ParseTuple(args, "O:CreateFileMoniker", &obName))
return NULL;
TmpWCHAR Name;
if (!PyWinObject_AsWCHAR(obName, &Name))
return NULL;
IMoniker *pmk;
PY_INTERFACE_PRECALL;
HRESULT hr = CreateFileMoniker(Name, &pmk);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pmk, IID_IMoniker, FALSE);
}
// @pymethod <o PyIMoniker>|pythoncom|CreateItemMoniker|Creates an item moniker
// that identifies an object within a containing object (typically a compound document).
static PyObject *pythoncom_CreateItemMoniker(PyObject *self, PyObject *args)
{
PyObject *obDelim, *obItem;
// @pyparm string|delim||String containing the delimiter (typically "!") used to separate this item's display name
// from the display name of its containing object.
// @pyparm string|item||String indicating the containing object's name for the object being identified.
if (!PyArg_ParseTuple(args, "OO:CreateItemMoniker", &obDelim, &obItem))
return NULL;
TmpWCHAR Delim, Item;
if (!PyWinObject_AsWCHAR(obDelim, &Delim, TRUE))
return NULL;
if (!PyWinObject_AsWCHAR(obItem, &Item, FALSE))
return NULL;
IMoniker *pmk;
PY_INTERFACE_PRECALL;
HRESULT hr = CreateItemMoniker(Delim, Item, &pmk);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pmk, IID_IMoniker, FALSE);
}
// @pymethod <o PyIMoniker>|pythoncom|CreateURLMonikerEx|Create a URL moniker from a full url or partial url and base
// moniker
// @pyseeapi CreateURLMonikerEx
static PyObject *pythoncom_CreateURLMonikerEx(PyObject *self, PyObject *args)
{
WCHAR *url = NULL;
PyObject *obbase, *oburl, *ret = NULL;
IMoniker *base_moniker = NULL, *output_moniker = NULL;
HRESULT hr;
DWORD flags = URL_MK_UNIFORM;
CHECK_PFN(CreateURLMonikerEx);
if (!PyArg_ParseTuple(args, "OO|k:CreateURLMonikerEx",
&obbase, // @pyparm <o PyIMoniker>|Context||An IMoniker interface to be used as a base with a
// partial URL, can be None
&oburl, // @pyparm <o PyUNICODE>|URL||Full or partial url for which to create a moniker
&flags)) // @pyparm int|Flags|URL_MK_UNIFORM|URL_MK_UNIFORM or URL_MK_LEGACY
return NULL;
if (!PyWinObject_AsWCHAR(oburl, &url, FALSE))
return NULL;
if (PyCom_InterfaceFromPyObject(obbase, IID_IMoniker, (LPVOID *)&base_moniker, TRUE)) {
PY_INTERFACE_PRECALL;
hr = (*pfnCreateURLMonikerEx)(base_moniker, url, &output_moniker, flags);
if (base_moniker)
base_moniker->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
PyCom_BuildPyException(hr);
else
ret = PyCom_PyObjectFromIUnknown(output_moniker, IID_IMoniker, FALSE);
}
PyWinObject_FreeWCHAR(url);
return ret;
}
// @pymethod <o PyIID>|pythoncom|GetClassFile|Supplies the CLSID associated with the given filename.
static PyObject *pythoncom_GetClassFile(PyObject *self, PyObject *args)
{
CLSID clsid;
PyObject *obFileName;
TmpWCHAR fname;
// @pyparm str|fileName||The filename for which you are requesting the associated CLSID.
if (!PyArg_ParseTuple(args, "O", &obFileName))
return NULL;
if (!PyWinObject_AsWCHAR(obFileName, &fname, FALSE))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = GetClassFile(fname, &clsid);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
return PyWinObject_FromIID(clsid);
}
// @pymethod |pythoncom|CoInitialize|Initialize the COM libraries for the calling thread.
static PyObject *pythoncom_CoInitialize(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":CoInitialize"))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = PyCom_CoInitialize(NULL);
PY_INTERFACE_POSTCALL;
// @rdesc This function will ignore the RPC_E_CHANGED_MODE error, as
// that error indicates someone else beat you to the initialization, and
// did so with a different threading model. This error is ignored as it
// still means COM is ready for use on this thread, and as this function
// does not explicitly specify a threading model the caller probably
// doesn't care what model it is.
// <nl>All other COM errors will raise pythoncom.error as usual. Use
// <om pythoncom.CoInitializeEx> if you also want to handle the RPC_E_CHANGED_MODE
// error.
if (FAILED(hr) && hr != RPC_E_CHANGED_MODE)
return PyCom_BuildPyException(hr);