-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathConverters.cxx
3565 lines (3133 loc) · 152 KB
/
Converters.cxx
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
// Bindings
#include "CPyCppyy.h"
#include "DeclareConverters.h"
#include "CallContext.h"
#include "CPPExcInstance.h"
#include "CPPInstance.h"
#include "CPPOverload.h"
#include "CustomPyTypes.h"
#include "LowLevelViews.h"
#include "MemoryRegulator.h"
#include "ProxyWrappers.h"
#include "PyStrings.h"
#include "TemplateProxy.h"
#include "TupleOfInstances.h"
#include "TypeManip.h"
#include "Utility.h"
// Standard
#include <complex>
#include <limits.h>
#include <stddef.h> // for ptrdiff_t
#include <string.h>
#include <algorithm>
#include <array>
#include <locale> // for wstring_convert
#include <regex>
#include <utility>
#include <sstream>
#if (__cplusplus > 201402L) || (defined(_MSC_VER) && _MSVC_LANG > 201402L)
#include <cstddef>
#include <string_view>
#endif
// codecvt does not exist for gcc4.8.5 and is in principle deprecated; it is
// only used in py2 for char -> wchar_t conversion for std::wstring; if not
// available, the conversion is done through Python (requires an extra copy)
#if PY_VERSION_HEX < 0x03000000
#if defined(__GNUC__) && !defined(__APPLE__)
# if __GNUC__ > 4 && __has_include("codecvt")
# include <codecvt>
# define HAS_CODECVT 1
# endif
#else
#include <codecvt>
#define HAS_CODECVT 1
#endif
#endif // py2
//- data _____________________________________________________________________
namespace CPyCppyy {
// factories
typedef std::map<std::string, cf_t> ConvFactories_t;
static ConvFactories_t gConvFactories;
// special objects
extern PyObject* gNullPtrObject;
extern PyObject* gDefaultObject;
// regular expression for matching function pointer
static std::regex s_fnptr("\\(:*\\*&*\\)");
}
#if PY_VERSION_HEX < 0x03000000
const Py_ssize_t MOVE_REFCOUNT_CUTOFF = 1;
#elif PY_VERSION_HEX < 0x03080000
// p3 has at least 2 ref-counts, as contrary to p2, it will create a descriptor
// copy for the method holding self in the case of __init__; but there can also
// be a reference held by the frame object, which is indistinguishable from a
// local variable reference, so the cut-off has to remain 2.
const Py_ssize_t MOVE_REFCOUNT_CUTOFF = 2;
#else
// since py3.8, vector calls behave again as expected
const Py_ssize_t MOVE_REFCOUNT_CUTOFF = 1;
#endif
//- pretend-ctypes helpers ---------------------------------------------------
struct CPyCppyy_tagCDataObject { // non-public (but stable)
PyObject_HEAD
char* b_ptr;
int b_needsfree;
};
struct CPyCppyy_tagPyCArgObject { // not public (but stable; note that older
PyObject_HEAD // Pythons protect 'D' with HAVE_LONG_LONG)
void* pffi_type;
char tag;
union { // for convenience, kept only relevant vals
long long q;
long double D;
void *p;
} value;
PyObject* obj;
};
// indices of ctypes types into the array caches (note that c_complex and c_fcomplex
// do not exist as types in ctypes)
#define ct_c_bool 0
#define ct_c_char 1
#define ct_c_shar 1
#define ct_c_wchar 2
#define ct_c_byte 3
#define ct_c_int8 3
#define ct_c_ubyte 4
#define ct_c_uchar 4
#define ct_c_uint8 4
#define ct_c_short 5
#define ct_c_ushort 6
#define ct_c_uint16 7
#define ct_c_int 8
#define ct_c_uint 9
#define ct_c_uint32 10
#define ct_c_long 11
#define ct_c_ulong 12
#define ct_c_longlong 13
#define ct_c_ulonglong 14
#define ct_c_float 15
#define ct_c_double 16
#define ct_c_longdouble 17
#define ct_c_char_p 18
#define ct_c_wchar_p 19
#define ct_c_void_p 20
#define ct_c_fcomplex 21
#define ct_c_complex 22
#define ct_c_pointer 23
#define NTYPES 24
static std::array<const char*, NTYPES> gCTypesNames = {
"c_bool", "c_char", "c_wchar", "c_byte", "c_ubyte", "c_short", "c_ushort", "c_uint16",
"c_int", "c_uint", "c_uint32", "c_long", "c_ulong", "c_longlong", "c_ulonglong",
"c_float", "c_double", "c_longdouble",
"c_char_p", "c_wchar_p", "c_void_p", "c_fcomplex", "c_complex", "_Pointer" };
static std::array<PyTypeObject*, NTYPES> gCTypesTypes;
static std::array<PyTypeObject*, NTYPES> gCTypesPtrTypes;
// Both GetCTypesType and GetCTypesPtrType, rely on the ctypes module itself
// caching the types (thus also making them unique), so no ref-count is needed.
// Further, by keeping a ref-count on the module, it won't be off-loaded until
// the 2nd cleanup cycle.
static PyTypeObject* GetCTypesType(int nidx)
{
static PyObject* ctmod = PyImport_ImportModule("ctypes"); // ref-count kept
if (!ctmod) {
PyErr_Clear();
return nullptr;
}
PyTypeObject* ct_t = gCTypesTypes[nidx];
if (!ct_t) {
ct_t = (PyTypeObject*)PyObject_GetAttrString(ctmod, gCTypesNames[nidx]);
if (!ct_t) PyErr_Clear();
else {
gCTypesTypes[nidx] = ct_t;
Py_DECREF(ct_t);
}
}
return ct_t;
}
static PyTypeObject* GetCTypesPtrType(int nidx)
{
static PyObject* ctmod = PyImport_ImportModule("ctypes"); // ref-count kept
if (!ctmod) {
PyErr_Clear();
return nullptr;
}
PyTypeObject* cpt_t = gCTypesPtrTypes[nidx];
if (!cpt_t) {
if (strcmp(gCTypesNames[nidx], "c_char") == 0) {
cpt_t = (PyTypeObject*)PyObject_GetAttrString(ctmod, "c_char_p");
} else {
PyObject* ct_t = (PyObject*)GetCTypesType(nidx);
if (ct_t) {
PyObject* ptrcreat = PyObject_GetAttrString(ctmod, "POINTER");
cpt_t = (PyTypeObject*)PyObject_CallFunctionObjArgs(ptrcreat, ct_t, NULL);
Py_DECREF(ptrcreat);
}
}
if (cpt_t) {
gCTypesPtrTypes[nidx] = cpt_t;
Py_DECREF(cpt_t);
}
}
return cpt_t;
}
static bool IsPyCArgObject(PyObject* pyobject)
{
static PyTypeObject* pycarg_type = nullptr;
if (!pycarg_type) {
PyObject* ctmod = PyImport_ImportModule("ctypes");
if (!ctmod) PyErr_Clear();
else {
PyTypeObject* ct_t = (PyTypeObject*)PyObject_GetAttrString(ctmod, "c_int");
PyObject* cobj = ct_t->tp_new(ct_t, nullptr, nullptr);
PyObject* byref = PyObject_GetAttrString(ctmod, "byref");
PyObject* pyptr = PyObject_CallFunctionObjArgs(byref, cobj, NULL);
Py_DECREF(byref); Py_DECREF(cobj); Py_DECREF(ct_t);
pycarg_type = Py_TYPE(pyptr); // static, no ref-count needed
Py_DECREF(pyptr);
Py_DECREF(ctmod);
}
}
return Py_TYPE(pyobject) == pycarg_type;
}
#if PY_VERSION_HEX < 0x30d0000
static bool IsCTypesArrayOrPointer(PyObject* pyobject)
{
static PyTypeObject* cstgdict_type = nullptr;
if (!cstgdict_type) {
// get any pointer type to initialize the extended dictionary type
PyTypeObject* ct_int = GetCTypesType(ct_c_int);
if (ct_int && ct_int->tp_dict) {
cstgdict_type = Py_TYPE(ct_int->tp_dict);
}
}
PyTypeObject* pytype = Py_TYPE(pyobject);
if (pytype->tp_dict && Py_TYPE(pytype->tp_dict) == cstgdict_type)
return true;
return false;
}
#else
// the internals of ctypes have been redone, requiring a more complex checking
namespace {
typedef struct {
PyTypeObject *DictRemover_Type;
PyTypeObject *PyCArg_Type;
PyTypeObject *PyCField_Type;
PyTypeObject *PyCThunk_Type;
PyTypeObject *StructParam_Type;
PyTypeObject *PyCType_Type;
PyTypeObject *PyCStructType_Type;
PyTypeObject *UnionType_Type;
PyTypeObject *PyCPointerType_Type;
// ... unused fields omitted ...
} _cppyy_ctypes_state;
} // unnamed namespace
static bool IsCTypesArrayOrPointer(PyObject* pyobject)
{
static _cppyy_ctypes_state* state = nullptr;
if (!state) {
PyObject* ctmod = PyImport_AddModule("_ctypes"); // the extension module, not the Python one
if (ctmod)
state = (_cppyy_ctypes_state*)PyModule_GetState(ctmod);
}
// verify for object types that have a C payload
if (state && (PyObject_IsInstance((PyObject*)Py_TYPE(pyobject), (PyObject*)state->PyCType_Type) ||
PyObject_IsInstance((PyObject*)Py_TYPE(pyobject), (PyObject*)state->PyCPointerType_Type))) {
return true;
}
return false;
}
#endif
//- helper to establish life lines -------------------------------------------
static inline bool SetLifeLine(PyObject* holder, PyObject* target, intptr_t ref)
{
// set a lifeline from on the holder to the target, using the ref as label
if (!holder) return false;
// 'ref' is expected to be the converter address or data memory location, so
// that the combination of holder and ref is unique, but also identifiable for
// reuse when the C++ side is being overwritten
std::ostringstream attr_name;
attr_name << "__" << ref;
auto res = PyObject_SetAttrString(holder, (char*)attr_name.str().c_str(), target);
return res != -1;
}
static bool HasLifeLine(PyObject* holder, intptr_t ref)
{
// determine if a lifeline was previously set for the ref on the holder
if (!holder) return false;
std::ostringstream attr_name;
attr_name << "__" << ref;
PyObject* res = PyObject_GetAttrString(holder, (char*)attr_name.str().c_str());
if (res) {
Py_DECREF(res);
return true;
}
PyErr_Clear();
return false;
}
//- helper to work with both CPPInstance and CPPExcInstance ------------------
static inline CPyCppyy::CPPInstance* GetCppInstance(
PyObject* pyobject, Cppyy::TCppType_t klass = (Cppyy::TCppType_t)0, bool accept_rvalue = false)
{
using namespace CPyCppyy;
if (CPPInstance_Check(pyobject))
return (CPPInstance*)pyobject;
if (CPPExcInstance_Check(pyobject))
return (CPPInstance*)((CPPExcInstance*)pyobject)->fCppInstance;
// this is not a C++ proxy; allow custom cast to C++
PyObject* castobj = PyObject_CallMethodNoArgs(pyobject, PyStrings::gCastCpp);
if (castobj) {
if (CPPInstance_Check(castobj))
return (CPPInstance*)castobj;
else if (klass && PyTuple_CheckExact(castobj)) {
// allow implicit conversion from a tuple of arguments
PyObject* pyclass = GetScopeProxy(klass);
if (pyclass) {
CPPInstance* pytmp = (CPPInstance*)PyObject_Call(pyclass, castobj, NULL);
Py_DECREF(pyclass);
if (CPPInstance_Check(pytmp)) {
if (accept_rvalue)
pytmp->fFlags |= CPPInstance::kIsRValue;
Py_DECREF(castobj);
return pytmp;
}
Py_XDECREF(pytmp);
}
}
Py_DECREF(castobj);
return nullptr;
}
PyErr_Clear();
return nullptr;
}
//- custom helpers to check ranges -------------------------------------------
static inline bool ImplicitBool(PyObject* pyobject, CPyCppyy::CallContext* ctxt)
{
using namespace CPyCppyy;
if (!AllowImplicit(ctxt) && PyBool_Check(pyobject)) {
if (!NoImplicit(ctxt)) ctxt->fFlags |= CallContext::kHaveImplicit;
return false;
}
return true;
}
static inline bool StrictBool(PyObject* pyobject, CPyCppyy::CallContext* ctxt)
{
using namespace CPyCppyy;
if (!AllowImplicit(ctxt) && !PyBool_Check(pyobject)) {
if (!NoImplicit(ctxt)) ctxt->fFlags |= CallContext::kHaveImplicit;
return false;
}
return true;
}
static inline bool CPyCppyy_PyLong_AsBool(PyObject* pyobject)
{
// range-checking python integer to C++ bool conversion
long l = PyLong_AsLong(pyobject);
// fail to pass float -> bool; the problem is rounding (0.1 -> 0 -> False)
if (!(l == 0|| l == 1) || PyFloat_Check(pyobject)) {
PyErr_SetString(PyExc_ValueError, "boolean value should be bool, or integer 1 or 0");
return (bool)-1;
}
return (bool)l;
}
// range-checking python integer to C++ integer conversion (prevents p2.7 silent conversions)
#define CPPYY_PYLONG_AS_TYPE(name, type, limit_low, limit_high) \
static inline type CPyCppyy_PyLong_As##name(PyObject* pyobject) \
{ \
if (!(PyLong_Check(pyobject) || PyInt_Check(pyobject))) { \
if (pyobject == CPyCppyy::gDefaultObject) \
return (type)0; \
PyErr_SetString(PyExc_TypeError, #type" conversion expects an integer object");\
return (type)-1; \
} \
long l = PyLong_AsLong(pyobject); \
if (l < limit_low || limit_high < l) { \
PyErr_Format(PyExc_ValueError, "integer %ld out of range for "#type, l);\
return (type)-1; \
} \
return (type)l; \
}
CPPYY_PYLONG_AS_TYPE(UInt8, uint8_t, 0, UCHAR_MAX)
CPPYY_PYLONG_AS_TYPE(Int8, int8_t, SCHAR_MIN, SCHAR_MAX)
CPPYY_PYLONG_AS_TYPE(UShort, unsigned short, 0, USHRT_MAX)
CPPYY_PYLONG_AS_TYPE(Short, short, SHRT_MIN, SHRT_MAX)
CPPYY_PYLONG_AS_TYPE(StrictInt, int, INT_MIN, INT_MAX)
static inline long CPyCppyy_PyLong_AsStrictLong(PyObject* pyobject)
{
// strict python integer to C++ long integer conversion
// prevent float -> long (see CPyCppyy_PyLong_AsStrictInt)
if (!(PyLong_Check(pyobject) || PyInt_Check(pyobject))) {
if (pyobject == CPyCppyy::gDefaultObject)
return (long)0;
PyErr_SetString(PyExc_TypeError, "int/long conversion expects an integer object");
return (long)-1;
}
return (long)PyLong_AsLong(pyobject); // already does long range check
}
static inline PY_LONG_LONG CPyCppyy_PyLong_AsStrictLongLong(PyObject* pyobject)
{
// strict python integer to C++ long long integer conversion
// prevent float -> long (see CPyCppyy_PyLong_AsStrictInt)
if (!(PyLong_Check(pyobject) || PyInt_Check(pyobject))) {
if (pyobject == CPyCppyy::gDefaultObject)
return (PY_LONG_LONG)0;
PyErr_SetString(PyExc_TypeError, "int/long conversion expects an integer object");
return (PY_LONG_LONG)-1;
}
return PyLong_AsLongLong(pyobject); // already does long range check
}
//- helper for pointer/array/reference conversions ---------------------------
static inline bool CArraySetArg(
PyObject* pyobject, CPyCppyy::Parameter& para, char tc, int size, bool check=true)
{
// general case of loading a C array pointer (void* + type code) as function argument
if (pyobject == CPyCppyy::gNullPtrObject || pyobject == CPyCppyy::gDefaultObject)
para.fValue.fVoidp = nullptr;
else {
Py_ssize_t buflen = CPyCppyy::Utility::GetBuffer(pyobject, tc, size, para.fValue.fVoidp, check);
if (!buflen) {
// stuck here as it's the least common
if (CPyCppyy_PyLong_AsStrictInt(pyobject) == 0)
para.fValue.fVoidp = nullptr;
else {
PyErr_Format(PyExc_TypeError, // ValueError?
"could not convert argument to buffer or nullptr");
return false;
}
}
}
para.fTypeCode = 'p';
return true;
}
//- helper for implicit conversions ------------------------------------------
static inline CPyCppyy::CPPInstance* ConvertImplicit(Cppyy::TCppType_t klass,
PyObject* pyobject, CPyCppyy::Parameter& para, CPyCppyy::CallContext* ctxt, bool manage=true)
{
using namespace CPyCppyy;
// filter out copy and move constructors
if (IsConstructor(ctxt->fFlags) && klass == ctxt->fCurScope && ctxt->GetSize() == 1)
return nullptr;
// only proceed if implicit conversions are allowed (in "round 2") or if the
// argument is exactly a tuple or list, as these are the equivalent of
// initializer lists and thus "syntax" not a conversion
if (!AllowImplicit(ctxt)) {
PyTypeObject* pytype = (PyTypeObject*)Py_TYPE(pyobject);
if (!(pytype == &PyList_Type || pytype == &PyTuple_Type)) {// || !CPPInstance_Check(pyobject))) {
if (!NoImplicit(ctxt)) ctxt->fFlags |= CallContext::kHaveImplicit;
return nullptr;
}
}
// exercise implicit conversion
PyObject* pyscope = CreateScopeProxy(klass);
if (!CPPScope_Check(pyscope)) {
Py_XDECREF(pyscope);
return nullptr;
}
// call constructor of argument type to attempt implicit conversion (disallow any
// implicit conversions by the scope's constructor itself)
PyObject* args = PyTuple_New(1);
Py_INCREF(pyobject); PyTuple_SET_ITEM(args, 0, pyobject);
((CPPScope*)pyscope)->fFlags |= CPPScope::kNoImplicit;
CPPInstance* pytmp = (CPPInstance*)PyObject_Call(pyscope, args, NULL);
if (!pytmp && PyTuple_CheckExact(pyobject)) {
// special case: allow implicit conversion from given set of arguments in tuple
PyErr_Clear();
pytmp = (CPPInstance*)PyObject_Call(pyscope, pyobject, NULL);
}
((CPPScope*)pyscope)->fFlags &= ~CPPScope::kNoImplicit;
Py_DECREF(args);
Py_DECREF(pyscope);
if (pytmp) {
// implicit conversion succeeded!
if (manage) ctxt->AddTemporary((PyObject*)pytmp);
para.fValue.fVoidp = pytmp->GetObjectRaw();
para.fTypeCode = 'V';
return pytmp;
}
PyErr_Clear();
return nullptr;
}
//- base converter implementation --------------------------------------------
CPyCppyy::Converter::~Converter()
{
/* empty */
}
//----------------------------------------------------------------------------
PyObject* CPyCppyy::Converter::FromMemory(void*)
{
// could happen if no derived class override
PyErr_SetString(PyExc_TypeError, "C++ type cannot be converted from memory");
return nullptr;
}
//----------------------------------------------------------------------------
bool CPyCppyy::Converter::ToMemory(PyObject*, void*, PyObject* /* ctxt */)
{
// could happen if no derived class override
PyErr_SetString(PyExc_TypeError, "C++ type cannot be converted to memory");
return false;
}
//- helper macro's -----------------------------------------------------------
#define CPPYY_IMPL_BASIC_CONVERTER_BODY(name, type, stype, ctype, F1, F2, tc)\
/* convert <pyobject> to C++ 'type', set arg for call */ \
type val = (type)F2(pyobject); \
if (val == (type)-1 && PyErr_Occurred()) { \
static PyTypeObject* ctypes_type = nullptr; \
if (!ctypes_type) { \
PyObject* pytype = 0, *pyvalue = 0, *pytrace = 0; \
PyErr_Fetch(&pytype, &pyvalue, &pytrace); \
ctypes_type = GetCTypesType(ct_##ctype); \
PyErr_Restore(pytype, pyvalue, pytrace); \
} \
if (Py_TYPE(pyobject) == ctypes_type) { \
PyErr_Clear(); \
val = *((type*)((CPyCppyy_tagCDataObject*)pyobject)->b_ptr); \
} else if (pyobject == CPyCppyy::gDefaultObject) { \
PyErr_Clear(); \
val = (type)0; \
} else \
return false; \
} \
para.fValue.f##name = val; \
para.fTypeCode = tc; \
return true;
#define CPPYY_IMPL_BASIC_CONVERTER_METHODS(name, type, stype, ctype, F1, F2) \
PyObject* CPyCppyy::name##Converter::FromMemory(void* address) \
{ \
return F1((stype)*((type*)address)); \
} \
\
bool CPyCppyy::name##Converter::ToMemory( \
PyObject* value, void* address, PyObject* /* ctxt */) \
{ \
type s = (type)F2(value); \
if (s == (type)-1 && PyErr_Occurred()) { \
if (value == CPyCppyy::gDefaultObject) { \
PyErr_Clear(); \
s = (type)0; \
} else \
return false; \
} \
*((type*)address) = (type)s; \
return true; \
}
#define CPPYY_IMPL_BASIC_CONVERTER_NI(name, type, stype, ctype, F1, F2, tc) \
bool CPyCppyy::name##Converter::SetArg( \
PyObject* pyobject, Parameter& para, CallContext* ctxt) \
{ \
if (!StrictBool(pyobject, ctxt)) \
return false; \
CPPYY_IMPL_BASIC_CONVERTER_BODY(name, type, stype, ctype, F1, F2, tc) \
} \
CPPYY_IMPL_BASIC_CONVERTER_METHODS(name, type, stype, ctype, F1, F2)
#define CPPYY_IMPL_BASIC_CONVERTER_IB(name, type, stype, ctype, F1, F2, tc) \
bool CPyCppyy::name##Converter::SetArg( \
PyObject* pyobject, Parameter& para, CallContext* ctxt) \
{ \
if (!ImplicitBool(pyobject, ctxt)) \
return false; \
CPPYY_IMPL_BASIC_CONVERTER_BODY(name, type, stype, ctype, F1, F2, tc) \
} \
CPPYY_IMPL_BASIC_CONVERTER_METHODS(name, type, stype, ctype, F1, F2)
#define CPPYY_IMPL_BASIC_CONVERTER_NB(name, type, stype, ctype, F1, F2, tc) \
bool CPyCppyy::name##Converter::SetArg( \
PyObject* pyobject, Parameter& para, CallContext* /*ctxt*/) \
{ \
if (PyBool_Check(pyobject)) \
return false; \
CPPYY_IMPL_BASIC_CONVERTER_BODY(name, type, stype, ctype, F1, F2, tc) \
} \
CPPYY_IMPL_BASIC_CONVERTER_METHODS(name, type, stype, ctype, F1, F2)
//----------------------------------------------------------------------------
static inline int ExtractChar(PyObject* pyobject, const char* tname, int low, int high)
{
int lchar = -1;
if (PyBytes_Check(pyobject)) {
if (PyBytes_GET_SIZE(pyobject) == 1)
lchar = (int)(PyBytes_AsString(pyobject)[0]);
else
PyErr_Format(PyExc_ValueError, "%s expected, got bytes of size " PY_SSIZE_T_FORMAT,
tname, PyBytes_GET_SIZE(pyobject));
} else if (CPyCppyy_PyText_Check(pyobject)) {
if (CPyCppyy_PyText_GET_SIZE(pyobject) == 1)
lchar = (int)(CPyCppyy_PyText_AsString(pyobject)[0]);
else
PyErr_Format(PyExc_ValueError, "%s expected, got str of size " PY_SSIZE_T_FORMAT,
tname, CPyCppyy_PyText_GET_SIZE(pyobject));
} else if (pyobject == CPyCppyy::gDefaultObject) {
lchar = (int)'\0';
} else if (!PyFloat_Check(pyobject)) { // don't allow truncating conversion
lchar = (int)PyLong_AsLong(pyobject);
if (lchar == -1 && PyErr_Occurred())
; // empty, as error already set
else if (!(low <= lchar && lchar <= high)) {
PyErr_Format(PyExc_ValueError,
"integer to character: value %d not in range [%d,%d]", lchar, low, high);
lchar = -1;
}
} else
PyErr_SetString(PyExc_TypeError, "char or small int type expected");
return lchar;
}
//----------------------------------------------------------------------------
#define CPPYY_IMPL_REFCONVERTER_FROM_MEMORY(name, ctype) \
PyObject* CPyCppyy::name##RefConverter::FromMemory(void* ptr) \
{ \
/* convert a reference to int to Python through ctypes pointer object */ \
PyTypeObject* ctypes_type = GetCTypesType(ct_##ctype); \
if (!ctypes_type) { \
PyErr_SetString(PyExc_RuntimeError, "no ctypes available"); \
return nullptr; \
} \
PyObject* ref = ctypes_type->tp_new(ctypes_type, nullptr, nullptr); \
((CPyCppyy_tagCDataObject*)ref)->b_ptr = (char*)ptr; \
((CPyCppyy_tagCDataObject*)ref)->b_needsfree = 0; \
return ref; \
}
//----------------------------------------------------------------------------
#define CPPYY_IMPL_BASIC_CONST_REFCONVERTER(name, type, ctype, F1) \
bool CPyCppyy::Const##name##RefConverter::SetArg( \
PyObject* pyobject, Parameter& para, CallContext* /* ctxt */) \
{ \
type val = (type)F1(pyobject); \
if (val == (type)-1 && PyErr_Occurred()) { \
if (pyobject == CPyCppyy::gDefaultObject) { \
PyErr_Clear(); \
val = (type)0; \
} else \
return false; \
} \
para.fValue.f##name = val; \
para.fRef = ¶.fValue.f##name; \
para.fTypeCode = 'r'; \
return true; \
} \
CPPYY_IMPL_REFCONVERTER_FROM_MEMORY(Const##name, ctype)
//----------------------------------------------------------------------------
#define CPPYY_IMPL_BASIC_CONST_CHAR_REFCONVERTER(name, type, ctype, low, high)\
bool CPyCppyy::Const##name##RefConverter::SetArg( \
PyObject* pyobject, Parameter& para, CallContext* /* ctxt */) \
{ \
/* convert <pyobject> to C++ <<type>>, set arg for call, allow int -> char */\
type val = (type)ExtractChar(pyobject, #type, low, high); \
if (val == (type)-1 && PyErr_Occurred()) \
return false; \
para.fValue.fLong = val; \
para.fTypeCode = 'l'; \
return true; \
} \
CPPYY_IMPL_REFCONVERTER_FROM_MEMORY(Const##name, ctype)
//----------------------------------------------------------------------------
#define CPPYY_IMPL_BASIC_CHAR_CONVERTER(name, type, low, high) \
bool CPyCppyy::name##Converter::SetArg( \
PyObject* pyobject, Parameter& para, CallContext* /* ctxt */) \
{ \
/* convert <pyobject> to C++ <<type>>, set arg for call, allow int -> char */\
long val = ExtractChar(pyobject, #type, low, high); \
if (val == -1 && PyErr_Occurred()) \
return false; \
para.fValue.fLong = val; \
para.fTypeCode = 'l'; \
return true; \
} \
\
PyObject* CPyCppyy::name##Converter::FromMemory(void* address) \
{ \
/* return char in "native" str type as that's more natural in use */ \
return CPyCppyy_PyText_FromFormat("%c", *((type*)address)); \
} \
\
bool CPyCppyy::name##Converter::ToMemory( \
PyObject* value, void* address, PyObject* /* ctxt */) \
{ \
Py_ssize_t len; \
const char* cstr = nullptr; \
if (PyBytes_Check(value)) \
PyBytes_AsStringAndSize(value, (char**)&cstr, &len); \
else \
cstr = CPyCppyy_PyText_AsStringAndSize(value, &len); \
if (cstr) { \
if (len != 1) { \
PyErr_Format(PyExc_TypeError, #type" expected, got string of size %zd", len);\
return false; \
} \
*((type*)address) = (type)cstr[0]; \
} else { \
PyErr_Clear(); \
long l = PyLong_AsLong(value); \
if (l == -1 && PyErr_Occurred()) { \
if (value == CPyCppyy::gDefaultObject) { \
PyErr_Clear(); \
l = (long)0; \
} else \
return false; \
} \
if (!(low <= l && l <= high)) { \
PyErr_Format(PyExc_ValueError, \
"integer to character: value %ld not in range [%d,%d]", l, low, high);\
return false; \
} \
*((type*)address) = (type)l; \
} \
return true; \
}
//- converters for built-ins -------------------------------------------------
CPPYY_IMPL_BASIC_CONVERTER_IB(Long, long, long, c_long, PyLong_FromLong, CPyCppyy_PyLong_AsStrictLong, 'l')
//----------------------------------------------------------------------------
bool CPyCppyy::LongRefConverter::SetArg(
PyObject* pyobject, Parameter& para, CallContext* /* ctxt */)
{
// convert <pyobject> to C++ long&, set arg for call
#if PY_VERSION_HEX < 0x03000000
if (RefInt_CheckExact(pyobject)) {
para.fValue.fVoidp = (void*)&((PyIntObject*)pyobject)->ob_ival;
para.fTypeCode = 'V';
return true;
}
#endif
if (Py_TYPE(pyobject) == GetCTypesType(ct_c_long)) {
para.fValue.fVoidp = (void*)((CPyCppyy_tagCDataObject*)pyobject)->b_ptr;
para.fTypeCode = 'V';
return true;
}
if (CArraySetArg(pyobject, para, 'l', sizeof(long))) {
para.fTypeCode = 'V';
return true;
}
PyErr_SetString(PyExc_TypeError, "use ctypes.c_long for pass-by-ref of longs");
return false;
}
//----------------------------------------------------------------------------
CPPYY_IMPL_BASIC_CONST_CHAR_REFCONVERTER(Char, char, c_char, CHAR_MIN, CHAR_MAX)
CPPYY_IMPL_BASIC_CONST_CHAR_REFCONVERTER(UChar, unsigned char, c_uchar, 0, UCHAR_MAX)
CPPYY_IMPL_BASIC_CONST_REFCONVERTER(Bool, bool, c_bool, CPyCppyy_PyLong_AsBool)
CPPYY_IMPL_BASIC_CONST_REFCONVERTER(Int8, int8_t, c_int8, CPyCppyy_PyLong_AsInt8)
CPPYY_IMPL_BASIC_CONST_REFCONVERTER(UInt8, uint8_t, c_uint8, CPyCppyy_PyLong_AsUInt8)
CPPYY_IMPL_BASIC_CONST_REFCONVERTER(Short, short, c_short, CPyCppyy_PyLong_AsShort)
CPPYY_IMPL_BASIC_CONST_REFCONVERTER(UShort, unsigned short, c_ushort, CPyCppyy_PyLong_AsUShort)
CPPYY_IMPL_BASIC_CONST_REFCONVERTER(Int, int, c_int, CPyCppyy_PyLong_AsStrictInt)
CPPYY_IMPL_BASIC_CONST_REFCONVERTER(UInt, unsigned int, c_uint, PyLongOrInt_AsULong)
CPPYY_IMPL_BASIC_CONST_REFCONVERTER(Long, long, c_long, CPyCppyy_PyLong_AsStrictLong)
CPPYY_IMPL_BASIC_CONST_REFCONVERTER(ULong, unsigned long, c_ulong, PyLongOrInt_AsULong)
CPPYY_IMPL_BASIC_CONST_REFCONVERTER(LLong, PY_LONG_LONG, c_longlong, CPyCppyy_PyLong_AsStrictLongLong)
CPPYY_IMPL_BASIC_CONST_REFCONVERTER(ULLong, PY_ULONG_LONG, c_ulonglong, PyLongOrInt_AsULong64)
//----------------------------------------------------------------------------
bool CPyCppyy::IntRefConverter::SetArg(
PyObject* pyobject, Parameter& para, CallContext* /* ctxt */)
{
// convert <pyobject> to C++ (pseudo)int&, set arg for call
#if PY_VERSION_HEX < 0x03000000
if (RefInt_CheckExact(pyobject)) {
para.fValue.fVoidp = (void*)&((PyIntObject*)pyobject)->ob_ival;
para.fTypeCode = 'V';
return true;
}
#endif
#if PY_VERSION_HEX >= 0x02050000
if (Py_TYPE(pyobject) == GetCTypesType(ct_c_int)) {
para.fValue.fVoidp = (void*)((CPyCppyy_tagCDataObject*)pyobject)->b_ptr;
para.fTypeCode = 'V';
return true;
}
#endif
// alternate, pass pointer from buffer
Py_ssize_t buflen = Utility::GetBuffer(pyobject, 'i', sizeof(int), para.fValue.fVoidp);
if (para.fValue.fVoidp && buflen) {
para.fTypeCode = 'V';
return true;
};
#if PY_VERSION_HEX < 0x02050000
PyErr_SetString(PyExc_TypeError, "use cppyy.Long for pass-by-ref of ints");
#else
PyErr_SetString(PyExc_TypeError, "use ctypes.c_int for pass-by-ref of ints");
#endif
return false;
}
//----------------------------------------------------------------------------
#define CPPYY_IMPL_REFCONVERTER(name, ctype, type, code) \
bool CPyCppyy::name##RefConverter::SetArg( \
PyObject* pyobject, Parameter& para, CallContext* /* ctxt */) \
{ \
/* convert a reference to int to Python through ctypes pointer object */ \
if (Py_TYPE(pyobject) == GetCTypesType(ct_##ctype)) { \
para.fValue.fVoidp = (void*)((CPyCppyy_tagCDataObject*)pyobject)->b_ptr;\
para.fTypeCode = 'V'; \
return true; \
} \
bool res = CArraySetArg(pyobject, para, code, sizeof(type)); \
if (!res) { \
PyErr_SetString(PyExc_TypeError, "use ctypes."#ctype" for pass-by-ref of "#type);\
return false; \
} \
para.fTypeCode = 'V'; \
return res; \
} \
CPPYY_IMPL_REFCONVERTER_FROM_MEMORY(name, ctype)
CPPYY_IMPL_REFCONVERTER(Bool, c_bool, bool, '?');
CPPYY_IMPL_REFCONVERTER(Char, c_char, char, 'b');
CPPYY_IMPL_REFCONVERTER(WChar, c_wchar, wchar_t, 'u');
CPPYY_IMPL_REFCONVERTER(Char16, c_uint16, char16_t, 'H');
CPPYY_IMPL_REFCONVERTER(Char32, c_uint32, char32_t, 'I');
CPPYY_IMPL_REFCONVERTER(SChar, c_byte, signed char, 'b');
CPPYY_IMPL_REFCONVERTER(UChar, c_ubyte, unsigned char, 'B');
CPPYY_IMPL_REFCONVERTER(Int8, c_int8, int8_t, 'b');
CPPYY_IMPL_REFCONVERTER(UInt8, c_uint8, uint8_t, 'B');
CPPYY_IMPL_REFCONVERTER(Short, c_short, short, 'h');
CPPYY_IMPL_REFCONVERTER(UShort, c_ushort, unsigned short, 'H');
CPPYY_IMPL_REFCONVERTER_FROM_MEMORY(Int, c_int);
CPPYY_IMPL_REFCONVERTER(UInt, c_uint, unsigned int, 'I');
CPPYY_IMPL_REFCONVERTER_FROM_MEMORY(Long, c_long);
CPPYY_IMPL_REFCONVERTER(ULong, c_ulong, unsigned long, 'L');
CPPYY_IMPL_REFCONVERTER(LLong, c_longlong, long long, 'q');
CPPYY_IMPL_REFCONVERTER(ULLong, c_ulonglong, unsigned long long, 'Q');
CPPYY_IMPL_REFCONVERTER(Float, c_float, float, 'f');
CPPYY_IMPL_REFCONVERTER_FROM_MEMORY(Double, c_double);
CPPYY_IMPL_REFCONVERTER(LDouble, c_longdouble, PY_LONG_DOUBLE, 'g');
//----------------------------------------------------------------------------
// convert <pyobject> to C++ bool, allow int/long -> bool, set arg for call
CPPYY_IMPL_BASIC_CONVERTER_NI(
Bool, bool, long, c_bool, PyBool_FromLong, CPyCppyy_PyLong_AsBool, 'l')
//----------------------------------------------------------------------------
CPPYY_IMPL_BASIC_CHAR_CONVERTER(Char, char, CHAR_MIN, CHAR_MAX)
CPPYY_IMPL_BASIC_CHAR_CONVERTER(UChar, unsigned char, 0, UCHAR_MAX)
PyObject* CPyCppyy::SCharAsIntConverter::FromMemory(void* address)
{
// special case to be used with arrays: return a Python int instead of str
// (following the same convention as module array.array)
return PyInt_FromLong((long)*((signed char*)address));
}
PyObject* CPyCppyy::UCharAsIntConverter::FromMemory(void* address)
{
// special case to be used with arrays: return a Python int instead of str
// (following the same convention as module array.array)
return PyInt_FromLong((long)*((unsigned char*)address));
}
//----------------------------------------------------------------------------
bool CPyCppyy::WCharConverter::SetArg(
PyObject* pyobject, Parameter& para, CallContext* /* ctxt */)
{
// convert <pyobject> to C++ <wchar_t>, set arg for call
if (!PyUnicode_Check(pyobject) || CPyCppyy_PyUnicode_GET_SIZE(pyobject) != 1) {
PyErr_SetString(PyExc_ValueError, "single wchar_t character expected");
return false;
}
wchar_t val;
Py_ssize_t res = CPyCppyy_PyUnicode_AsWideChar(pyobject, &val, 1);
if (res == -1)
return false;
para.fValue.fLong = (long)val;
para.fTypeCode = 'U';
return true;
}
PyObject* CPyCppyy::WCharConverter::FromMemory(void* address)
{
return PyUnicode_FromWideChar((const wchar_t*)address, 1);
}
bool CPyCppyy::WCharConverter::ToMemory(PyObject* value, void* address, PyObject* /* ctxt */)
{
if (!PyUnicode_Check(value) || CPyCppyy_PyUnicode_GET_SIZE(value) != 1) {
PyErr_SetString(PyExc_ValueError, "single wchar_t character expected");
return false;
}
wchar_t val;
Py_ssize_t res = CPyCppyy_PyUnicode_AsWideChar(value, &val, 1);
if (res == -1)
return false;
*((wchar_t*)address) = val;
return true;
}
//----------------------------------------------------------------------------
bool CPyCppyy::Char16Converter::SetArg(
PyObject* pyobject, Parameter& para, CallContext* /* ctxt */)
{
// convert <pyobject> to C++ <char16_t>, set arg for call
if (!PyUnicode_Check(pyobject) || CPyCppyy_PyUnicode_GET_SIZE(pyobject) != 1) {
PyErr_SetString(PyExc_ValueError, "single char16_t character expected");
return false;
}
PyObject* bstr = PyUnicode_AsUTF16String(pyobject);
if (!bstr) return false;
char16_t val = *(char16_t*)(PyBytes_AS_STRING(bstr) + sizeof(char16_t) /*BOM*/);
Py_DECREF(bstr);
para.fValue.fLong = (long)val;
para.fTypeCode = 'U';
return true;
}
PyObject* CPyCppyy::Char16Converter::FromMemory(void* address)
{
return PyUnicode_DecodeUTF16((const char*)address, sizeof(char16_t), nullptr, nullptr);
}
bool CPyCppyy::Char16Converter::ToMemory(PyObject* value, void* address, PyObject* /* ctxt */)
{
if (!PyUnicode_Check(value) || CPyCppyy_PyUnicode_GET_SIZE(value) != 1) {
PyErr_SetString(PyExc_ValueError, "single char16_t character expected");
return false;
}
PyObject* bstr = PyUnicode_AsUTF16String(value);
if (!bstr) return false;
*((char16_t*)address) = *(char16_t*)(PyBytes_AS_STRING(bstr) + sizeof(char16_t) /*BOM*/);
Py_DECREF(bstr);
return true;
}
//----------------------------------------------------------------------------
bool CPyCppyy::Char32Converter::SetArg(
PyObject* pyobject, Parameter& para, CallContext* /* ctxt */)
{
// convert <pyobject> to C++ <char32_t>, set arg for call
if (!PyUnicode_Check(pyobject) || 2 < CPyCppyy_PyUnicode_GET_SIZE(pyobject)) {
PyErr_SetString(PyExc_ValueError, "single char32_t character expected");
return false;
}
PyObject* bstr = PyUnicode_AsUTF32String(pyobject);
if (!bstr) return false;
char32_t val = *(char32_t*)(PyBytes_AS_STRING(bstr) + sizeof(char32_t) /*BOM*/);
Py_DECREF(bstr);
para.fValue.fLong = (long)val;
para.fTypeCode = 'U';
return true;
}
PyObject* CPyCppyy::Char32Converter::FromMemory(void* address)
{
return PyUnicode_DecodeUTF32((const char*)address, sizeof(char32_t), nullptr, nullptr);
}
bool CPyCppyy::Char32Converter::ToMemory(PyObject* value, void* address, PyObject* /* ctxt */)
{