-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefbase.py
More file actions
3307 lines (2686 loc) · 96.3 KB
/
Copy pathdefbase.py
File metadata and controls
3307 lines (2686 loc) · 96.3 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
"""
`defbase.py`
Library core module, defining all
architecture, typing interfaces,
helper functions, C++ infrastructure and
abstraction helpers.
"""
from typing import (Callable, Any, List,
Union as TUnion, Generic, TypeVar,
Type, Dict, Optional, ClassVar, Self,
Protocol, overload, TYPE_CHECKING)
from functools import wraps
import typing_extensions as defb_tx
import typing as defb_t
import types as defb_ty
import warnings
__all__ = [
"declare",
"unicode",
"module_to_namespace",
"using_namespace",
"IPointer",
"IFunction",
"i_cast",
"foreign",
"link_library",
"IInterface",
"THIS",
"AccessError",
"W_WinDLL",
"W_CDLL",
"foreign_optimized",
"VirtualTable",
"IDoublePtr",
"reinterpret_cast",
"static_cast",
"PtrArithmetic",
"PtrUtil",
"std",
"CStructure",
"WinWarning",
"AccessError",
"Ref",
"Template",
"W_OleDLL",
"W_PyDLL",
"AssertTool",
"CClass",
"ASSERT",
"array_after_structure",
"POINTER",
"PTR",
"DOUBLE_PTR",
"delegate",
"TemplateFunction",
"get_template",
"TUnion",
"get_py_frame",
"get_caller_frame",
"IArray",
"INamespace",
"get_library",
"get_win_library",
"filter_self",
"CUnion",
"CFuncPtr",
"declare_fields",
"byref",
"IVoidPtr",
"interface_abstract_method",
"c_void_p",
"i_cast2",
"WT", "WT2",
"WT_ADDRLIKE",
"IInteger",
"IChar",
"IWideChar",
"IAliasable",
"IAliasableGeneric",
"IShort", "IUnsignedShort",
"IInt", "IUnsignedInt",
"ILong", "IUnsignedLong",
"IInt64", "IUnsignedInt64",
"ISizeT", "ISignedSizeT",
"IArrayFixedSize",
"ICustomizable",
"IBool", "IBool64",
"IFloat", "IDouble",
"IInt32", "IUnsignedInt32",
"IInt16", "IUnsignedInt16",
"IInt8", "IUnsignedInt8",
"reset_annotations",
"IAnonymous",
"IPack",
"IAliasableGenericWithPayload",
"format_hex",
"WT_LPSTR", "WT_LPWSTR",
"IUlong", "IULong",
"IUint", "IUInt",
"IUshort", "IUShort",
"IByte", "IWord",
"IDword", "IQword",
"IUnsignedLongLong", "ILongLong",
"IULongLong", "IUlonglong",
"IUInt8", "IUint8",
"IUInt16", "IUint16",
"IUInt32", "IUint32",
"IUInt64", "IUint64",
"IIntPtr", "ILongPtr",
"IDwordPtr", "IUhalfPtr",
"IUIntPtr", "IUnsignedIntPtr", "IUintPtr",
"IUnsignedHalfPtr", "IUHalfPtr",
"IUnsignedLongPtr", "IULongPtr", "IUlongPtr",
"IHandle",
"ICharArray", "IWideCharArray",
"WT_HANDLE", "flexible_array",
"LI",
"IWideCharArrayFixedSize", "ICharArrayFixedSize",
"add_annotation", "remove_annotations",
"size_annotations",
"IVoidPtrT",
"field_typed",
"is_null",
"DelayedMarshaller",
"call_variadic",
"resolve_type", "resolve_genericalias",
"ipointer_to_pointer",
"is_genericalias",
"genericalias_single_type",
"genericalias_types",
"IGenericAlias",
"is_IFunction",
"is_IFunctionType",
"DelayedTypeStorage",
"i_cast_structure",
"IMarshallable",
"IReferenceable",
"IUnpackable",
"IMarshaller",
"get_current_frame",
"ITraceEntry",
"trace_enable",
"trace_disable",
"trace_add",
"trace_remove",
"SupportsGet", "SupportsSet",
"SupportsGetSet",
"hot_reload_module",
"suppress_WinWarning", "unsuppress_WinWarning",
"NullFunction",
"pcall",
"i_getattr", "i_setattr",
"WinAttribute", "WinProperty", "WinPropertyStore", "attributes",
"i_cast_value",
"IExceptHook",
"excepthook_enable",
"excepthook_disable",
"excepthook_add",
"excepthook_remove",
"excepthook_super",
"IUnraisableHook",
"unraisablehook_enable",
"unraisablehook_disable",
"unraisablehook_add",
"unraisablehook_remove",
"unraisablehook_super",
"IHasInit",
"NEVER",
"WT_STRUCTURE",
"WT_SIMPLESTRUCTURE",
"IProfileEntry",
"profile_enable",
"profile_disable",
"profile_add",
"profile_remove",
"defb_t", "defb_tx",
"WTC", "WTCT", "WTCT_S", "WTCT_V", "WTCT2",
"defb_ty",
"is_CData", "is_CFuncPtr",
"CData", "SimpleCData",
"PTRD",
"is_float_like", "is_int_like"
]
def pcall(f, *args, **kwargs) -> tuple[Any, BaseException]:
try:
return f(*args, **kwargs), None
except BaseException as be:
return None, be
from . import cpreproc
_WT_UNSTABLE_API = cpreproc.defined('WT_UNSTABLE_API')
if _WT_UNSTABLE_API:
__all__.extend([
'cbyref', 'CByref',
'CVoidP'
])
class _DEFB_STATE: # internal global state
__slots__ = ['_linked_libraries', '_defbase_process',
'_defbase_module', '_interfacedef', '_unknwn',
'_provider', '_wet_trace', '_prev_trace',
'_trace_enabled', '_trace_entries', '_suppress_winwarning',
'_local_allocator', '_prev_excepthook', '_excepthook_enabled',
'_excepthook_entries', '_prev_unraisablehook',
'_unraisablehook_enabled', '_unraisablehook_entries',
'_prev_profile', '_profile_enabled', '_profile_entries',]
_trace_entries: list['ITraceEntry']
_profile_entries: list['IProfileEntry']
_prev_profile: Any
_linked_libraries: Dict[str, 'LI']
_prev_trace: Any
_prev_excepthook: Any
_excepthook_entries: list['IExceptHook']
_prev_unraisablehook: Any
_unraisablehook_entries: list['IUnraisableHook']
def __init__(self):
self._linked_libraries = {}
self._prev_trace = None
self._trace_enabled = False
self._trace_entries = []
self._suppress_winwarning = False
self._local_allocator = None
self._prev_excepthook = None
self._excepthook_enabled = False
self._excepthook_entries = []
self._prev_unraisablehook = None
self._unraisablehook_enabled = False
self._unraisablehook_entries = []
self._prev_profile = None
self._profile_enabled = False
self._profile_entries = []
_defb_state: _DEFB_STATE = _DEFB_STATE()
def format_hex(value: int, zeros: int = -1) -> str:
"""
Format the hexadecimal value with leading `zeros`.
"""
if value is None:
if zeros == -1:
return '0x0'
return '0x' + '0'.zfill(zeros)
if zeros == -1:
return hex(value)
value &= ((1 << (zeros << 3)) - 1)
return '0x' + (hex(value)[2:].zfill(zeros))
if TYPE_CHECKING:
from ctypes import _CData
from _ctypes import _PyCSimpleType, _PyCStructType
from ctypes import _CDataType
from ctypes import _CData as CData, _SimpleCData as SimpleCData, _CDataType as CDataType
from _ctypes import (_PyCSimpleType as PyCSimpleType,
_PyCStructType as PyCStructType,
_PyCFuncPtrType as PyCFuncPtrType,
_PyCArrayType as PyCArrayType,
_Pointer as Pointer, _CField as CField,
_CArgObject as CArgObject, Array)
else:
from ctypes import Structure, c_int, POINTER, byref
from ctypes.wintypes import RECT
from _ctypes import CFuncPtr
_CData = CData = Structure.__base__
_PyCStructType = PyCStructType = Structure.__class__
_PyCSimpleType = PyCSimpleType = c_int.__class__
CArgObject = byref(c_int()).__class__
CField = type(RECT.left)
SimpleCData = c_int.__base__
PyCArrayType = (c_int * 0).__class__
Array = (c_int * 0).__base__
Pointer = POINTER(c_int).__base__
PyCPointerType = Pointer.__class__
PyCFuncPtrType = CFuncPtr.__class__
# Core generic functionality
WT = TypeVar('_WT')
WT2 = TypeVar('_WT2')
WTC = TypeVar('_WTC', bound=_CData)
WTCT = TypeVar('_WTCT', bound='_CDataType')
WTCT_S = TypeVar('_WTCT_S', bound=_PyCStructType)
WTCT_V = TypeVar('_WTCT_V', bound=_PyCSimpleType)
WTCT2 = TypeVar('_WTCT2', bound='_CDataType')
def interface_abstract_method(f: WT) -> WT:
"""
Declare the interface method as abstract.
"""
@wraps(f)
def _interface_abstract_method(*args, **kwargs):
raise RuntimeError(f"'{f.__qualname__}' method is abstract.")
_interface_abstract_method._abstract = True
return _interface_abstract_method
def suppress_WinWarning():
"""
Suppress the `WinWarning`.
"""
_defb_state._suppress_winwarning = True
def unsuppress_WinWarning():
"""
Unsuppress the `WinWarning`
"""
_defb_state._suppress_winwarning = False
class IInterface:
"""
Base class for type-safe typing interfaces.
"""
@interface_abstract_method
def __init__(self): ...
@staticmethod
def is_abstract(method: Callable) -> bool:
"""
Check the given method is abstract
(declared with a `@interface_abstract_method`).
"""
return hasattr(method, '_abstract')
class INamespace:
"""
Base class for "namespaces", they are not instantiable.
"""
@interface_abstract_method
def __init__(self): ...
# IFunctionType is now migrated to `IFunction`,
# `is_IFunctionType` left because no function to check
# is object an `ctypes` function type.
def is_IFunctionType(cls: type) -> bool:
"""
Check the `cls` function type is IFunctionType-compatible.
"""
return (isinstance(cls, type) and
hasattr(cls, '_argtypes_') and
hasattr(cls, '_restype_') and
hasattr(cls, '_flags_'))
class IFunction(IInterface):
"""
Type-safe interface over
ctypes library function.
"""
def __call__(*args: Any, **kwargs: Any):
"""
Call the `IFunction`.
"""
# IFunction
argtypes: List[type]
restype: type
flags: type
# IFunctionType-migrated
_argtypes_: ClassVar[List[type]]
_restype_: ClassVar[type]
_flags_: ClassVar[int]
def is_IFunction(instance: Any) -> bool:
"""
Check the `instance` function type is IFunction-compatible.
"""
return (not isinstance(instance, type) and
hasattr(instance, 'argtypes') and
hasattr(instance, 'restype'))
def is_CData(instance: Any) -> bool:
"""
Check the `instance` type is CData descendant (ctypes-compatible).
"""
return isinstance(instance, _CData)
def is_CFuncPtr(instance: Any) -> bool:
"""
Check the `instance` type is CData descendant (ctypescall-compatible).
"""
return isinstance(instance, CFuncPtr)
class IMarshaller(IInterface):
"""
Interface to represent the object can be marshaller.
"""
@interface_abstract_method
def marshal_value(self, value: Any) -> Any:
"""
Marshal given value into type.
"""
@interface_abstract_method
@classmethod
def static_marshal_value(self, value: Any) -> Any:
"""
Marshal given value into type. Static version of method.
"""
@classmethod
def is_marshaller(self, marshaller: Callable | 'IMarshaller' | Any) -> bool:
"""
Check given value is marshaller-compatible. Must not be overriden.
"""
return isinstance(marshaller, IMarshaller) or callable(marshaller)
@classmethod
def call_marshaller(self, value: Any, marshaller: Callable | 'IMarshaller') -> Any:
"""
Call the given marshaller on type. Must not be overriden.
"""
if isinstance(marshaller, IMarshaller):
return marshaller.marshal_value(value)
elif callable(marshaller):
return marshaller(value)
raise TypeError(type(marshaller))
class IMarshallable(IInterface):
"""
Interface to represent the marshalling-allowed object.
"""
@interface_abstract_method
def marshal(self, typ: type | IMarshaller) -> Any:
"""
Marshal object to given type.
"""
class IUnpackable(IInterface):
"""
Interface to represent the object can be unpacked to another object.
"""
@interface_abstract_method
def unpack(self) -> Any:
"""
Unpack object to another object.
"""
class IReferenceable(IInterface):
"""
Interface to represent the object that can putted
by pure object in function, that is waiting reference.
"""
# Object side
@interface_abstract_method
def get_reference(self) -> Any:
"""
Get reference to object.
"""
@interface_abstract_method
def allow_other_type(self, typ: type) -> bool:
"""
Is allowed to reference the object if
receiving type is not `IReferenceable`.
"""
# Type side
@interface_abstract_method
@classmethod
def allow_reference(self, value) -> bool:
"""
Is type allowing value to be referenced.
Must be implemented if used as type, otherwise not.
"""
@interface_abstract_method
@classmethod
def dereference(cls, reference: 'IPointer') -> Any:
"""
Dereference the given reference.
"""
class DelayedMarshaller(IMarshaller):
"""
Delayed Marshaller for marshal schemes.
Lazely initialized by caller.
"""
marshal_func: Callable
def __init__(self):
self.marshal_func = None
def __call__(self, *args) -> Any:
return self.marshal_func(*args)
def marshal(self, value: Any) -> Any:
return self.marshal_func(value)
class DelayedTypeStorage(IUnpackable):
"""
Delayed Type Storage.
Lazely initialized by caller.
"""
storaged_type: type[WT]
def __init__(self):
self.storaged_type = None
def __call__(self, *args, **kwargs) -> Any:
return self.storaged_type(*args, **kwargs)
def unpack(self) -> type[WT]:
return self.storaged_type
def call_variadic(function: IFunction, variadic_scheme: list[type], *args) -> Any:
"""
Call variadic function with provided variadic scheme.
"""
old = function.argtypes
function.argtypes = list(function.argtypes) + variadic_scheme
result = function(*args)
function.argtypes = old
return result
import types
import sys
def get_current_frame():
"""
Get current Python frame.
"""
return sys._getframe(1)
def get_py_frame(depth: int):
"""
Get Python frame at depth.
"""
return sys._getframe(depth+1)
def get_caller_frame():
"""
Get caller Python frame.
"""
return sys._getframe(2)
class ITraceEntry(IInterface):
"""
Interface for subscribing on trace calls.
"""
@interface_abstract_method
def on_event(self, frame: types.FrameType, event: str, arg: Any):
"""
Callback, called on every trace function call.
"""
def _trace_routine(frame: types.FrameType, event: str, arg: Any) -> Callable:
for entry in _defb_state._trace_entries:
entry.on_event(frame, event, arg)
return _trace_routine
def trace_enable():
"""
Enable trace.
"""
_defb_state._prev_trace = sys.gettrace()
_defb_state._trace_enabled = True
sys.settrace(_trace_routine)
def trace_disable():
"""
Disable trace.
"""
sys.settrace(_defb_state._prev_trace)
_defb_state._trace_enabled = False
_defb_state._prev_trace = None
def trace_add(entry: type[ITraceEntry]):
"""
Add the entry to trace listeners.
"""
_defb_state._trace_entries.append(entry)
def trace_remove(entry: type[ITraceEntry]):
"""
Remove the entry from trace listeners.
"""
_defb_state._trace_entries.remove(entry)
class IProfileEntry(IInterface):
"""
Interface for subscribing on profile calls.
"""
@interface_abstract_method
def on_event(self, frame: types.FrameType, event: str, arg: Any):
"""
Callback, called on every profile function call.
"""
def _profile_routine(frame: types.FrameType, event: str, arg: Any) -> Callable:
for entry in _defb_state._profile_entries:
entry.on_event(frame, event, arg)
return _profile_routine
def profile_enable():
"""
Enable profile.
"""
_defb_state._prev_profile = sys.getprofile()
_defb_state._profile_enabled = True
sys.settrace(_profile_routine)
def profile_disable():
"""
Disable profile.
"""
sys.setprofile(_defb_state._prev_profile)
_defb_state._profile_enabled = False
_defb_state._prev_profile = None
def profile_add(entry: type[ITraceEntry]):
"""
Add the entry to profile listeners.
"""
_defb_state._profile_entries.append(entry)
def profile_remove(entry: type[IProfileEntry]):
"""
Remove the entry from profile listeners.
"""
_defb_state._profile_entries.remove(entry)
class IHasInit(IInterface):
"""
Interface describing class is has empty constructor and not an interface at final.
"""
def __init__(*args): ...
class IExceptHook(IInterface):
"""
Interface for subscribing on except hook.
"""
@interface_abstract_method
def on_exception(self, type: type[BaseException], value: BaseException, traceback: types.TracebackType):
"""
Callback, called on unhandled exception.
"""
class IUnraisableHook(IInterface):
"""
Interface for subscribing on unraisable hook.
"""
@interface_abstract_method
def on_unraisable_exception(self, args: 'sys.UnraisableHookArgs'):
"""
Callback, called on unraisable exception.
"""
def _excepthook_routine(type: type[BaseException], value: BaseException, traceback: types.TracebackType) -> Callable:
for entry in _defb_state._excepthook_entries:
entry.on_exception(type, value, traceback)
def excepthook_super(type: type[BaseException], value: BaseException, traceback: types.TracebackType):
"""
Call super function on except hook.
"""
return sys.__excepthook__(type, value, traceback)
def excepthook_enable():
"""
Enable except hook.
"""
_defb_state._prev_excepthook = sys.excepthook
_defb_state._excepthook_enabled = True
sys.excepthook = _excepthook_routine
def excepthook_disable():
"""
Disable except hook.
"""
sys.excepthook = _defb_state._prev_excepthook
_defb_state._excepthook_enabled = False
_defb_state._prev_excepthook = None
def excepthook_add(entry: type[IExceptHook]):
"""
Add the entry to except hook listeners.
"""
_defb_state._excepthook_entries.append(entry)
def excepthook_remove(entry: type[IExceptHook]):
"""
Remove the entry from except hook listeners.
"""
_defb_state._excepthook_entries.remove(entry)
def _unraisablehook_routine(args: 'sys.UnraisableHookArgs') -> Callable:
for entry in _defb_state._unraisablehook_entries:
entry.on_unraisable_exception(args)
def unraisablehook_super(args: 'sys.UnraisableHookArgs'):
"""
Call super function on unraisable hook.
"""
return sys.__unraisablehook__(args)
def unraisablehook_enable():
"""
Enable unraisable hook.
"""
_defb_state._prev_unraisablehook = sys.unraisablehook
_defb_state._unraisablehook_enabled = True
sys.unraisablehook = _unraisablehook_routine
def unraisablehook_disable():
"""
Disable unraisable hook.
"""
sys.unraisablehook = _defb_state._prev_unraisablehook
_defb_state._unraisablehook_enabled = False
_defb_state._prev_unraisablehook = None
def unraisablehook_add(entry: type[IUnraisableHook]):
"""
Add the entry to unraisable hook listeners.
"""
_defb_state._unraisablehook_entries.append(entry)
def unraisablehook_remove(entry: type[IUnraisableHook]):
"""
Remove the entry from unraisable hook listeners.
"""
_defb_state._unraisablehook_entries.remove(entry)
from ctypes import Structure, byref, POINTER as _POINTER, pointer, c_int, c_void_p
from _ctypes import CFuncPtr
class IArray(IInterface, Generic[WT]):
"""
Type-safe interface over
ctypes array.
"""
@interface_abstract_method
def __getitem__(self, index: int) -> WT: ...
@interface_abstract_method
def __setitem__(self, index: int, value: WT) -> WT: ...
class IArrayFixedSize(IInterface, Generic[WT, WT2]):
"""
Type-safe interface over
ctypes array by fixed size
(for @CStructure.make).
"""
@interface_abstract_method
def __getitem__(self, index: int) -> WT: ...
@interface_abstract_method
def __setitem__(self, index: int, value: WT) -> WT: ...
class IPointer(IArray[WT]):
"""
Type-safe interface over
ctypes pointer.
"""
contents: WT
from typing import TypeAlias, Tuple, Mapping
IDoublePtr: TypeAlias = IPointer[IPointer[WT]]
class IVoidPtr(IInterface):
"""
Type-safe interface over
ctypes void* pointer.
"""
value: int
class IVoidPtrT(IInterface, int):
"""
Type-safe interface over
typed (unmarshalled) ctypes
void* pointer.
"""
def define_extended_type(cls):
"""
Define extended type with support of `__static_cast__`.
"""
@staticmethod
def from_param(param):
static_cast = getattr(param, '__static_cast__', None)
if static_cast is None:
return super(cls, cls).from_param(param)
result = static_cast(cls)
if result is NotImplemented:
return super(cls, cls).from_param(param)
return result
cls.from_param = from_param
return cls
# # # # # # # # # # # # # # # # # # #
# CPython-Specific part begins !!! #
# # # # # # # # # # # # # # # # # # #
# initialize DefbCI
from . import _defbase_ctypinit
_defbase_ctypinit.Init()
if _WT_UNSTABLE_API:
from _ctypes import _SimpleCData as SimpleCData
class ICData(IInterface):
_b_base_: int
_b_needsfree_: bool
_objects: Mapping[Any, int] | None
def __buffer__(self, flags: int, /) -> memoryview: ...
def __ctypes_from_outparam__(self, /) -> Self: ...
# don't know how to bypass ctypes check
# for only _CArgObject type and not its
# descendant. This API is marked as unstable
# so DON'T use this (if you want, use this, but i awared you).
class CByref(_defbase_ctypinit.CArgObject, IPointer[WT]):
"""
## <!> UNSTABLE API !!!
Enhanced byref class over CArgObject.
Implements IPointer and IArray typing interfaces.
"""
_carg: _defbase_ctypinit.PyCArgObject
@property
def contents(self) -> WT:
"""## <!> UNSTABLE API !!!"""
return self.ptr().contents
@contents.setter
def contents(self, contents: WT):
"""## <!> UNSTABLE API !!!"""
self.ptr().contents = _ptr_to_type(self)(contents)
self._obj.value = contents
def __getitem__(self, index: int) -> WT:
return self.ptr()[index]
def __setitem__(self, index: int, value: WT):
if index == 0 and hasattr(self._obj, 'value'):
self._obj.value = _ptr_to_type(self)(value)
self.ptr()[index] = value
def ptr(self) -> IPointer[WT]:
"""
## <!> UNSTABLE API !!!
Explicitly convert byref type to
normal ctypes pointer.
"""
return i_cast(self, PTR(_ptr_to_type(self)))
@classmethod
def make(cls, obj: ICData) -> Optional['CByref']:
"""
## <!> UNSTABLE API !!!
Make the CByref enhanced reference to object (CData).
"""
if not isinstance(obj, CData):
raise TypeError('expected CData instance')
parg: IPointer[_defbase_ctypinit.PyCArgObject[CByref]]
parg = _defbase_ctypinit.New_PyCArgObject(CByref)
if parg is None:
return None
cbyref: CByref = _defbase_ctypinit.Init_PyCArgObject(parg, obj)
cbyref._carg = parg.contents
return cbyref
def cbyref(obj: WT) -> CByref[WT]:
"""
## <!> UNSTABLE API !!!
Get the CByref enhanced sreference to object.
"""
return CByref.make(obj)
# is not fully compatible with ctypes
# so i don't know how to deal with it.
# This API is marked as unstable
# so DON'T use this (if you want, use this, but i awared you).
class CVoidP(c_void_p, IVoidPtr):
"""
## <!> UNSTABLE API !!!
The enhanced `c_void_p` implementation
that supports `CByref` enhanced references.
"""
@classmethod
def from_param(cls, param):
if isinstance(param, CByref):
if _defbase_ctypinit.PyCArgObject_CAST_DEREF(param).tag == b'P':
return param
return super().from_param(param)
def __repr__(self) -> str:
return f'<CVoidP address={format_hex(PtrUtil.get_address(self), sizeof(c_void_p))}>'
# c_void_p = CVoidP
# # # # # # # # # # # # # # # # # # #
# CPython-Specific part ends !!! #
# # # # # # # # # # # # # # # # # # #
def PTR(typ: Type[WT]) -> Type[IPointer[WT]]:
"""
Make the pointer to type.
"""
if typ is None: return c_void_p
if issubclass(typ, c_wchar):
return c_wchar_p
if issubclass(typ, c_char):
return c_char_p
return _POINTER(typ)
def PTRD(typ: Type[WT]) -> Type[IPointer[WT]]:
"""
Directly make the pointer to type.
"""
return _POINTER(typ)
def DOUBLE_PTR(typ: Type[WT]) -> Type[IDoublePtr[WT]]:
"""
Make the double pointer to type. Shortcut for `PTR(PTR(type))`.
"""
return PTR(PTR(typ))
# alias (for compatibility) instead of dumb `ctypes.POINTER`
POINTER = PTR
from ctypes import WINFUNCTYPE
class VirtualTable:
"""
Class representing interface to C++ Virtual table.
"""
class _FuncPtr(CFuncPtr):
_restype_ = c_int
_flags_ = 0x0
VType: type['CStructure']
field_name: str
fields: list
name: str
func_ptr: Type[CFuncPtr] = _FuncPtr
@classmethod
def from_ancestor(cls, ancestor: Self, name: str) -> Self:
"""
Initialize descendant virtual table from ancestor virtual table.
"""
virtual_table = cls(name)
virtual_table.fields.extend(ancestor.fields)
return virtual_table