1 /*****************************************************************
2 This file should be kept compatible with Python 2.3, see PEP 291.
3 *****************************************************************/
9 Get rid of the checker (and also the converters) field in PyCFuncPtrObject and
10 StgDictObject, and replace them by slot functions in StgDictObject.
12 think about a buffer-like object (memory? bytes?)
14 Should POINTER(c_char) and POINTER(c_wchar) have a .value property?
15 What about c_char and c_wchar arrays then?
17 Add from_mmap, from_file, from_string metaclass methods.
19 Maybe we can get away with from_file (calls read) and with a from_buffer
22 And what about the to_mmap, to_file, to_str(?) methods? They would clobber
23 the namespace, probably. So, functions instead? And we already have memmove...
28 Name methods, members, getsets
29 ==============================================================================
31 PyCStructType_Type __new__(), from_address(), __mul__(), from_param()
32 UnionType_Type __new__(), from_address(), __mul__(), from_param()
33 PyCPointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type()
34 PyCArrayType_Type __new__(), from_address(), __mul__(), from_param()
35 PyCSimpleType_Type __new__(), from_address(), __mul__(), from_param()
38 Struct_Type __new__(), __init__()
39 PyCPointer_Type __new__(), __init__(), _as_parameter_, contents
40 PyCArray_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__()
41 Simple_Type __new__(), __init__(), _as_parameter_
46 ==============================================================================
51 It has some similarity to the byref() construct compared to pointer()
53 - construct an instance from a given memory block (sharing this memory block)
56 - typecheck and convert a Python object into a C function call parameter
57 the result may be an instance of the type, or an integer or tuple
58 (typecode, value[, obj])
60 instance methods/properties
61 ---------------------------
64 - convert self into a C function call parameter
65 This is either an integer, or a 3-tuple (typecode, value, obj)
71 - return the number of bytes the buffer contains
74 - return the number of bytes the buffer of an instance would contain
85 - return the buffer contents as a sequence of bytes (which is currently a string)
107 #define PY_SSIZE_T_CLEAN
110 #include "structmember.h"
116 #ifndef IS_INTRESOURCE
117 #define IS_INTRESOURCE(x) (((size_t)(x) >> 16) == 0)
120 /* Unlike desktop Windows, WinCE has both W and A variants of
121 GetProcAddress, but the default W version is not what we want */
122 # undef GetProcAddress
123 # define GetProcAddress GetProcAddressA
126 #include "ctypes_dlfcn.h"
130 PyObject
*PyExc_ArgError
;
132 /* This dict maps ctypes types to POINTER types */
133 PyObject
*_ctypes_ptrtype_cache
;
135 static PyTypeObject Simple_Type
;
137 /* a callable object used for unpickling */
138 static PyObject
*_unpickle
;
140 char *_ctypes_conversion_encoding
= NULL
;
141 char *_ctypes_conversion_errors
= NULL
;
144 /****************************************************************/
146 #if (PY_VERSION_HEX < 0x02040000)
147 /* Only in Python 2.4 and up */
149 PyTuple_Pack(int n
, ...)
158 result
= PyTuple_New(n
);
161 items
= ((PyTupleObject
*)result
)->ob_item
;
162 for (i
= 0; i
< n
; i
++) {
163 o
= va_arg(vargs
, PyObject
*);
172 /****************************************************************/
181 _DictRemover_dealloc(PyObject
*_self
)
183 DictRemoverObject
*self
= (DictRemoverObject
*)_self
;
184 Py_XDECREF(self
->key
);
185 Py_XDECREF(self
->dict
);
186 Py_TYPE(self
)->tp_free(_self
);
190 _DictRemover_call(PyObject
*_self
, PyObject
*args
, PyObject
*kw
)
192 DictRemoverObject
*self
= (DictRemoverObject
*)_self
;
193 if (self
->key
&& self
->dict
) {
194 if (-1 == PyDict_DelItem(self
->dict
, self
->key
))
195 /* XXX Error context */
196 PyErr_WriteUnraisable(Py_None
);
197 Py_DECREF(self
->key
);
199 Py_DECREF(self
->dict
);
206 static PyTypeObject DictRemover_Type
= {
207 PyVarObject_HEAD_INIT(NULL
, 0)
208 "_ctypes.DictRemover", /* tp_name */
209 sizeof(DictRemoverObject
), /* tp_basicsize */
211 _DictRemover_dealloc
, /* tp_dealloc */
217 0, /* tp_as_number */
218 0, /* tp_as_sequence */
219 0, /* tp_as_mapping */
221 _DictRemover_call
, /* tp_call */
225 0, /* tp_as_buffer */
226 /* XXX should participate in GC? */
227 Py_TPFLAGS_DEFAULT
, /* tp_flags */
228 "deletes a key from a dictionary", /* tp_doc */
231 0, /* tp_richcompare */
232 0, /* tp_weaklistoffset */
240 0, /* tp_descr_get */
241 0, /* tp_descr_set */
242 0, /* tp_dictoffset */
250 PyDict_SetItemProxy(PyObject
*dict
, PyObject
*key
, PyObject
*item
)
253 DictRemoverObject
*remover
;
257 obj
= PyObject_CallObject((PyObject
*)&DictRemover_Type
, NULL
);
261 remover
= (DictRemoverObject
*)obj
;
262 assert(remover
->key
== NULL
);
263 assert(remover
->dict
== NULL
);
267 remover
->dict
= dict
;
269 proxy
= PyWeakref_NewProxy(item
, obj
);
274 result
= PyDict_SetItem(dict
, key
, proxy
);
280 PyDict_GetItemProxy(PyObject
*dict
, PyObject
*key
)
283 PyObject
*item
= PyDict_GetItem(dict
, key
);
287 if (!PyWeakref_CheckProxy(item
))
289 result
= PyWeakref_GET_OBJECT(item
);
290 if (result
== Py_None
)
295 /******************************************************************/
297 Allocate a memory block for a pep3118 format string, copy prefix (if
298 non-null) and suffix into it. Returns NULL on failure, with the error
299 indicator set. If called with a suffix of NULL the error indicator must
303 _ctypes_alloc_format_string(const char *prefix
, const char *suffix
)
308 if (suffix
== NULL
) {
309 assert(PyErr_Occurred());
312 len
= strlen(suffix
);
314 len
+= strlen(prefix
);
315 result
= PyMem_Malloc(len
+ 1);
319 strcpy(result
, prefix
);
322 strcat(result
, suffix
);
327 PyCStructType_Type - a meta type/class. Creating a new class using this one as
328 __metaclass__ will call the contructor StructUnionType_new. It replaces the
329 tp_dict member with a new instance of StgDict, and initializes the C
330 accessible fields somehow.
333 static PyCArgObject
*
334 StructUnionType_paramfunc(CDataObject
*self
)
337 StgDictObject
*stgdict
;
339 parg
= PyCArgObject_new();
344 stgdict
= PyObject_stgdict((PyObject
*)self
);
345 assert(stgdict
); /* Cannot be NULL for structure/union instances */
346 parg
->pffi_type
= &stgdict
->ffi_type_pointer
;
347 /* For structure parameters (by value), parg->value doesn't contain the structure
348 data itself, instead parg->value.p *points* to the structure's data
349 See also _ctypes.c, function _call_function_pointer().
351 parg
->value
.p
= self
->b_ptr
;
352 parg
->size
= self
->b_size
;
354 parg
->obj
= (PyObject
*)self
;
359 StructUnionType_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
, int isStruct
)
361 PyTypeObject
*result
;
365 /* create the new instance (which is a class,
366 since we are a metatype!) */
367 result
= (PyTypeObject
*)PyType_Type
.tp_new(type
, args
, kwds
);
371 /* keep this for bw compatibility */
372 if (PyDict_GetItemString(result
->tp_dict
, "_abstract_"))
373 return (PyObject
*)result
;
375 dict
= (StgDictObject
*)PyObject_CallObject((PyObject
*)&PyCStgDict_Type
, NULL
);
380 /* replace the class dict by our updated stgdict, which holds info
381 about storage requirements of the instances */
382 if (-1 == PyDict_Update((PyObject
*)dict
, result
->tp_dict
)) {
384 Py_DECREF((PyObject
*)dict
);
387 Py_DECREF(result
->tp_dict
);
388 result
->tp_dict
= (PyObject
*)dict
;
389 dict
->format
= _ctypes_alloc_format_string(NULL
, "B");
390 if (dict
->format
== NULL
) {
395 dict
->paramfunc
= StructUnionType_paramfunc
;
397 fields
= PyDict_GetItemString((PyObject
*)dict
, "_fields_");
399 StgDictObject
*basedict
= PyType_stgdict((PyObject
*)result
->tp_base
);
401 if (basedict
== NULL
)
402 return (PyObject
*)result
;
404 if (-1 == PyCStgDict_clone(dict
, basedict
)) {
408 dict
->flags
&= ~DICTFLAG_FINAL
; /* clear the 'final' flag in the subclass dict */
409 basedict
->flags
|= DICTFLAG_FINAL
; /* set the 'final' flag in the baseclass dict */
410 return (PyObject
*)result
;
413 if (-1 == PyObject_SetAttrString((PyObject
*)result
, "_fields_", fields
)) {
417 return (PyObject
*)result
;
421 PyCStructType_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
423 return StructUnionType_new(type
, args
, kwds
, 1);
427 UnionType_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
429 return StructUnionType_new(type
, args
, kwds
, 0);
432 static char from_address_doc
[] =
433 "C.from_address(integer) -> C instance\naccess a C instance at the specified address";
436 CDataType_from_address(PyObject
*type
, PyObject
*value
)
439 if (!PyInt_Check(value
) && !PyLong_Check(value
)) {
440 PyErr_SetString(PyExc_TypeError
,
444 buf
= (void *)PyLong_AsVoidPtr(value
);
445 if (PyErr_Occurred())
447 return PyCData_AtAddress(type
, buf
);
450 static char from_buffer_doc
[] =
451 "C.from_buffer(object, offset=0) -> C instance\ncreate a C instance from a writeable buffer";
454 KeepRef(CDataObject
*target
, Py_ssize_t index
, PyObject
*keep
);
457 CDataType_from_buffer(PyObject
*type
, PyObject
*args
)
460 Py_ssize_t buffer_len
;
461 Py_ssize_t offset
= 0;
462 PyObject
*obj
, *result
;
463 StgDictObject
*dict
= PyType_stgdict(type
);
466 if (!PyArg_ParseTuple(args
,
467 #if (PY_VERSION_HEX < 0x02050000)
475 if (-1 == PyObject_AsWriteBuffer(obj
, &buffer
, &buffer_len
))
479 PyErr_SetString(PyExc_ValueError
,
480 "offset cannot be negative");
483 if (dict
->size
> buffer_len
- offset
) {
484 PyErr_Format(PyExc_ValueError
,
485 #if (PY_VERSION_HEX < 0x02050000)
486 "Buffer size too small (%d instead of at least %d bytes)",
488 "Buffer size too small (%zd instead of at least %zd bytes)",
490 buffer_len
, dict
->size
+ offset
);
494 result
= PyCData_AtAddress(type
, (char *)buffer
+ offset
);
499 if (-1 == KeepRef((CDataObject
*)result
, -1, obj
)) {
506 static char from_buffer_copy_doc
[] =
507 "C.from_buffer_copy(object, offset=0) -> C instance\ncreate a C instance from a readable buffer";
510 GenericPyCData_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
513 CDataType_from_buffer_copy(PyObject
*type
, PyObject
*args
)
516 Py_ssize_t buffer_len
;
517 Py_ssize_t offset
= 0;
518 PyObject
*obj
, *result
;
519 StgDictObject
*dict
= PyType_stgdict(type
);
522 if (!PyArg_ParseTuple(args
,
523 #if (PY_VERSION_HEX < 0x02050000)
531 if (-1 == PyObject_AsReadBuffer(obj
, &buffer
, &buffer_len
))
535 PyErr_SetString(PyExc_ValueError
,
536 "offset cannot be negative");
540 if (dict
->size
> buffer_len
- offset
) {
541 PyErr_Format(PyExc_ValueError
,
542 #if (PY_VERSION_HEX < 0x02050000)
543 "Buffer size too small (%d instead of at least %d bytes)",
545 "Buffer size too small (%zd instead of at least %zd bytes)",
547 buffer_len
, dict
->size
+ offset
);
551 result
= GenericPyCData_new((PyTypeObject
*)type
, NULL
, NULL
);
554 memcpy(((CDataObject
*)result
)->b_ptr
,
555 (char *)buffer
+offset
, dict
->size
);
559 static char in_dll_doc
[] =
560 "C.in_dll(dll, name) -> C instance\naccess a C instance in a dll";
563 CDataType_in_dll(PyObject
*type
, PyObject
*args
)
571 if (!PyArg_ParseTuple(args
, "Os:in_dll", &dll
, &name
))
574 obj
= PyObject_GetAttrString(dll
, "_handle");
577 if (!PyInt_Check(obj
) && !PyLong_Check(obj
)) {
578 PyErr_SetString(PyExc_TypeError
,
579 "the _handle attribute of the second argument must be an integer");
583 handle
= (void *)PyLong_AsVoidPtr(obj
);
585 if (PyErr_Occurred()) {
586 PyErr_SetString(PyExc_ValueError
,
587 "could not convert the _handle attribute to a pointer");
592 address
= (void *)GetProcAddress(handle
, name
);
594 PyErr_Format(PyExc_ValueError
,
595 "symbol '%s' not found",
600 address
= (void *)ctypes_dlsym(handle
, name
);
603 /* dlerror() isn't very helpful on cygwin */
604 PyErr_Format(PyExc_ValueError
,
605 "symbol '%s' not found (%s) ",
608 PyErr_SetString(PyExc_ValueError
, ctypes_dlerror());
613 return PyCData_AtAddress(type
, address
);
616 static char from_param_doc
[] =
617 "Convert a Python object into a function call parameter.";
620 CDataType_from_param(PyObject
*type
, PyObject
*value
)
622 PyObject
*as_parameter
;
623 if (1 == PyObject_IsInstance(value
, type
)) {
627 if (PyCArg_CheckExact(value
)) {
628 PyCArgObject
*p
= (PyCArgObject
*)value
;
629 PyObject
*ob
= p
->obj
;
632 dict
= PyType_stgdict(type
);
634 /* If we got a PyCArgObject, we must check if the object packed in it
635 is an instance of the type's dict->proto */
637 && PyObject_IsInstance(ob
, dict
->proto
)) {
641 ob_name
= (ob
) ? Py_TYPE(ob
)->tp_name
: "???";
642 PyErr_Format(PyExc_TypeError
,
643 "expected %s instance instead of pointer to %s",
644 ((PyTypeObject
*)type
)->tp_name
, ob_name
);
648 as_parameter
= PyObject_GetAttrString(value
, "_as_parameter_");
650 value
= CDataType_from_param(type
, as_parameter
);
651 Py_DECREF(as_parameter
);
654 PyErr_Format(PyExc_TypeError
,
655 "expected %s instance instead of %s",
656 ((PyTypeObject
*)type
)->tp_name
,
657 Py_TYPE(value
)->tp_name
);
661 static PyMethodDef CDataType_methods
[] = {
662 { "from_param", CDataType_from_param
, METH_O
, from_param_doc
},
663 { "from_address", CDataType_from_address
, METH_O
, from_address_doc
},
664 { "from_buffer", CDataType_from_buffer
, METH_VARARGS
, from_buffer_doc
, },
665 { "from_buffer_copy", CDataType_from_buffer_copy
, METH_VARARGS
, from_buffer_copy_doc
, },
666 { "in_dll", CDataType_in_dll
, METH_VARARGS
, in_dll_doc
},
671 CDataType_repeat(PyObject
*self
, Py_ssize_t length
)
674 return PyErr_Format(PyExc_ValueError
,
675 #if (PY_VERSION_HEX < 0x02050000)
676 "Array length must be >= 0, not %d",
678 "Array length must be >= 0, not %zd",
681 return PyCArrayType_from_ctype(self
, length
);
684 static PySequenceMethods CDataType_as_sequence
= {
685 0, /* inquiry sq_length; */
686 0, /* binaryfunc sq_concat; */
687 CDataType_repeat
, /* intargfunc sq_repeat; */
688 0, /* intargfunc sq_item; */
689 0, /* intintargfunc sq_slice; */
690 0, /* intobjargproc sq_ass_item; */
691 0, /* intintobjargproc sq_ass_slice; */
692 0, /* objobjproc sq_contains; */
694 0, /* binaryfunc sq_inplace_concat; */
695 0, /* intargfunc sq_inplace_repeat; */
699 CDataType_clear(PyTypeObject
*self
)
701 StgDictObject
*dict
= PyType_stgdict((PyObject
*)self
);
703 Py_CLEAR(dict
->proto
);
704 return PyType_Type
.tp_clear((PyObject
*)self
);
708 CDataType_traverse(PyTypeObject
*self
, visitproc visit
, void *arg
)
710 StgDictObject
*dict
= PyType_stgdict((PyObject
*)self
);
712 Py_VISIT(dict
->proto
);
713 return PyType_Type
.tp_traverse((PyObject
*)self
, visit
, arg
);
717 PyCStructType_setattro(PyObject
*self
, PyObject
*key
, PyObject
*value
)
719 /* XXX Should we disallow deleting _fields_? */
720 if (-1 == PyType_Type
.tp_setattro(self
, key
, value
))
723 if (value
&& PyString_Check(key
) &&
724 0 == strcmp(PyString_AS_STRING(key
), "_fields_"))
725 return PyCStructUnionType_update_stgdict(self
, value
, 1);
731 UnionType_setattro(PyObject
*self
, PyObject
*key
, PyObject
*value
)
733 /* XXX Should we disallow deleting _fields_? */
734 if (-1 == PyObject_GenericSetAttr(self
, key
, value
))
737 if (PyString_Check(key
) &&
738 0 == strcmp(PyString_AS_STRING(key
), "_fields_"))
739 return PyCStructUnionType_update_stgdict(self
, value
, 0);
744 PyTypeObject PyCStructType_Type
= {
745 PyVarObject_HEAD_INIT(NULL
, 0)
746 "_ctypes.PyCStructType", /* tp_name */
747 0, /* tp_basicsize */
755 0, /* tp_as_number */
756 &CDataType_as_sequence
, /* tp_as_sequence */
757 0, /* tp_as_mapping */
762 PyCStructType_setattro
, /* tp_setattro */
763 0, /* tp_as_buffer */
764 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
, /* tp_flags */
765 "metatype for the CData Objects", /* tp_doc */
766 (traverseproc
)CDataType_traverse
, /* tp_traverse */
767 (inquiry
)CDataType_clear
, /* tp_clear */
768 0, /* tp_richcompare */
769 0, /* tp_weaklistoffset */
772 CDataType_methods
, /* tp_methods */
777 0, /* tp_descr_get */
778 0, /* tp_descr_set */
779 0, /* tp_dictoffset */
782 PyCStructType_new
, /* tp_new */
786 static PyTypeObject UnionType_Type
= {
787 PyVarObject_HEAD_INIT(NULL
, 0)
788 "_ctypes.UnionType", /* tp_name */
789 0, /* tp_basicsize */
797 0, /* tp_as_number */
798 &CDataType_as_sequence
, /* tp_as_sequence */
799 0, /* tp_as_mapping */
804 UnionType_setattro
, /* tp_setattro */
805 0, /* tp_as_buffer */
806 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
, /* tp_flags */
807 "metatype for the CData Objects", /* tp_doc */
808 (traverseproc
)CDataType_traverse
, /* tp_traverse */
809 (inquiry
)CDataType_clear
, /* tp_clear */
810 0, /* tp_richcompare */
811 0, /* tp_weaklistoffset */
814 CDataType_methods
, /* tp_methods */
819 0, /* tp_descr_get */
820 0, /* tp_descr_set */
821 0, /* tp_dictoffset */
824 UnionType_new
, /* tp_new */
829 /******************************************************************/
833 The PyCPointerType_Type metaclass must ensure that the subclass of Pointer can be
834 created. It must check for a _type_ attribute in the class. Since are no
835 runtime created properties, a CField is probably *not* needed ?
837 class IntPointer(Pointer):
840 The PyCPointer_Type provides the functionality: a contents method/property, a
841 size property/method, and the sequence protocol.
846 PyCPointerType_SetProto(StgDictObject
*stgdict
, PyObject
*proto
)
848 if (!proto
|| !PyType_Check(proto
)) {
849 PyErr_SetString(PyExc_TypeError
,
850 "_type_ must be a type");
853 if (!PyType_stgdict(proto
)) {
854 PyErr_SetString(PyExc_TypeError
,
855 "_type_ must have storage info");
859 Py_XDECREF(stgdict
->proto
);
860 stgdict
->proto
= proto
;
864 static PyCArgObject
*
865 PyCPointerType_paramfunc(CDataObject
*self
)
869 parg
= PyCArgObject_new();
874 parg
->pffi_type
= &ffi_type_pointer
;
876 parg
->obj
= (PyObject
*)self
;
877 parg
->value
.p
= *(void **)self
->b_ptr
;
882 PyCPointerType_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
884 PyTypeObject
*result
;
885 StgDictObject
*stgdict
;
889 typedict
= PyTuple_GetItem(args
, 2);
893 stgdict items size, align, length contain info about pointers itself,
894 stgdict->proto has info about the pointed to type!
896 stgdict
= (StgDictObject
*)PyObject_CallObject(
897 (PyObject
*)&PyCStgDict_Type
, NULL
);
900 stgdict
->size
= sizeof(void *);
901 stgdict
->align
= _ctypes_get_fielddesc("P")->pffi_type
->alignment
;
903 stgdict
->ffi_type_pointer
= ffi_type_pointer
;
904 stgdict
->paramfunc
= PyCPointerType_paramfunc
;
905 stgdict
->flags
|= TYPEFLAG_ISPOINTER
;
907 proto
= PyDict_GetItemString(typedict
, "_type_"); /* Borrowed ref */
908 if (proto
&& -1 == PyCPointerType_SetProto(stgdict
, proto
)) {
909 Py_DECREF((PyObject
*)stgdict
);
914 StgDictObject
*itemdict
= PyType_stgdict(proto
);
916 /* If itemdict->format is NULL, then this is a pointer to an
917 incomplete type. We create a generic format string
918 'pointer to bytes' in this case. XXX Better would be to
919 fix the format string later...
921 stgdict
->format
= _ctypes_alloc_format_string("&",
922 itemdict
->format
? itemdict
->format
: "B");
923 if (stgdict
->format
== NULL
) {
924 Py_DECREF((PyObject
*)stgdict
);
929 /* create the new instance (which is a class,
930 since we are a metatype!) */
931 result
= (PyTypeObject
*)PyType_Type
.tp_new(type
, args
, kwds
);
932 if (result
== NULL
) {
933 Py_DECREF((PyObject
*)stgdict
);
937 /* replace the class dict by our updated spam dict */
938 if (-1 == PyDict_Update((PyObject
*)stgdict
, result
->tp_dict
)) {
940 Py_DECREF((PyObject
*)stgdict
);
943 Py_DECREF(result
->tp_dict
);
944 result
->tp_dict
= (PyObject
*)stgdict
;
946 return (PyObject
*)result
;
951 PyCPointerType_set_type(PyTypeObject
*self
, PyObject
*type
)
955 dict
= PyType_stgdict((PyObject
*)self
);
958 if (-1 == PyCPointerType_SetProto(dict
, type
))
961 if (-1 == PyDict_SetItemString((PyObject
*)dict
, "_type_", type
))
968 staticforward PyObject
*_byref(PyObject
*);
971 PyCPointerType_from_param(PyObject
*type
, PyObject
*value
)
973 StgDictObject
*typedict
;
975 if (value
== Py_None
) {
976 /* ConvParam will convert to a NULL pointer later */
981 typedict
= PyType_stgdict(type
);
982 assert(typedict
); /* Cannot be NULL for pointer types */
984 /* If we expect POINTER(<type>), but receive a <type> instance, accept
985 it by calling byref(<type>).
987 switch (PyObject_IsInstance(value
, typedict
->proto
)) {
989 Py_INCREF(value
); /* _byref steals a refcount */
990 return _byref(value
);
998 if (PointerObject_Check(value
) || ArrayObject_Check(value
)) {
999 /* Array instances are also pointers when
1000 the item types are the same.
1002 StgDictObject
*v
= PyObject_stgdict(value
);
1003 assert(v
); /* Cannot be NULL for pointer or array objects */
1004 if (PyObject_IsSubclass(v
->proto
, typedict
->proto
)) {
1009 return CDataType_from_param(type
, value
);
1012 static PyMethodDef PyCPointerType_methods
[] = {
1013 { "from_address", CDataType_from_address
, METH_O
, from_address_doc
},
1014 { "from_buffer", CDataType_from_buffer
, METH_VARARGS
, from_buffer_doc
, },
1015 { "from_buffer_copy", CDataType_from_buffer_copy
, METH_VARARGS
, from_buffer_copy_doc
, },
1016 { "in_dll", CDataType_in_dll
, METH_VARARGS
, in_dll_doc
},
1017 { "from_param", (PyCFunction
)PyCPointerType_from_param
, METH_O
, from_param_doc
},
1018 { "set_type", (PyCFunction
)PyCPointerType_set_type
, METH_O
},
1022 PyTypeObject PyCPointerType_Type
= {
1023 PyVarObject_HEAD_INIT(NULL
, 0)
1024 "_ctypes.PyCPointerType", /* tp_name */
1025 0, /* tp_basicsize */
1026 0, /* tp_itemsize */
1033 0, /* tp_as_number */
1034 &CDataType_as_sequence
, /* tp_as_sequence */
1035 0, /* tp_as_mapping */
1039 0, /* tp_getattro */
1040 0, /* tp_setattro */
1041 0, /* tp_as_buffer */
1042 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
, /* tp_flags */
1043 "metatype for the Pointer Objects", /* tp_doc */
1044 (traverseproc
)CDataType_traverse
, /* tp_traverse */
1045 (inquiry
)CDataType_clear
, /* tp_clear */
1046 0, /* tp_richcompare */
1047 0, /* tp_weaklistoffset */
1049 0, /* tp_iternext */
1050 PyCPointerType_methods
, /* tp_methods */
1055 0, /* tp_descr_get */
1056 0, /* tp_descr_set */
1057 0, /* tp_dictoffset */
1060 PyCPointerType_new
, /* tp_new */
1065 /******************************************************************/
1070 PyCArrayType_new ensures that the new Array subclass created has a _length_
1071 attribute, and a _type_ attribute.
1075 CharArray_set_raw(CDataObject
*self
, PyObject
*value
)
1079 if (PyBuffer_Check(value
)) {
1080 size
= Py_TYPE(value
)->tp_as_buffer
->bf_getreadbuffer(value
, 0, (void *)&ptr
);
1083 } else if (-1 == PyString_AsStringAndSize(value
, &ptr
, &size
)) {
1086 if (size
> self
->b_size
) {
1087 PyErr_SetString(PyExc_ValueError
,
1092 memcpy(self
->b_ptr
, ptr
, size
);
1098 CharArray_get_raw(CDataObject
*self
)
1100 return PyString_FromStringAndSize(self
->b_ptr
, self
->b_size
);
1104 CharArray_get_value(CDataObject
*self
)
1107 char *ptr
= self
->b_ptr
;
1108 for (i
= 0; i
< self
->b_size
; ++i
)
1111 return PyString_FromStringAndSize(self
->b_ptr
, i
);
1115 CharArray_set_value(CDataObject
*self
, PyObject
*value
)
1120 if (value
== NULL
) {
1121 PyErr_SetString(PyExc_TypeError
,
1122 "can't delete attribute");
1126 if (PyUnicode_Check(value
)) {
1127 value
= PyUnicode_AsEncodedString(value
,
1128 _ctypes_conversion_encoding
,
1129 _ctypes_conversion_errors
);
1132 } else if (!PyString_Check(value
)) {
1133 PyErr_Format(PyExc_TypeError
,
1134 "string expected instead of %s instance",
1135 Py_TYPE(value
)->tp_name
);
1139 size
= PyString_GET_SIZE(value
);
1140 if (size
> self
->b_size
) {
1141 PyErr_SetString(PyExc_ValueError
,
1147 ptr
= PyString_AS_STRING(value
);
1148 memcpy(self
->b_ptr
, ptr
, size
);
1149 if (size
< self
->b_size
)
1150 self
->b_ptr
[size
] = '\0';
1156 static PyGetSetDef CharArray_getsets
[] = {
1157 { "raw", (getter
)CharArray_get_raw
, (setter
)CharArray_set_raw
,
1159 { "value", (getter
)CharArray_get_value
, (setter
)CharArray_set_value
,
1164 #ifdef CTYPES_UNICODE
1166 WCharArray_get_value(CDataObject
*self
)
1169 wchar_t *ptr
= (wchar_t *)self
->b_ptr
;
1170 for (i
= 0; i
< self
->b_size
/sizeof(wchar_t); ++i
)
1171 if (*ptr
++ == (wchar_t)0)
1173 return PyUnicode_FromWideChar((wchar_t *)self
->b_ptr
, i
);
1177 WCharArray_set_value(CDataObject
*self
, PyObject
*value
)
1179 Py_ssize_t result
= 0;
1181 if (value
== NULL
) {
1182 PyErr_SetString(PyExc_TypeError
,
1183 "can't delete attribute");
1186 if (PyString_Check(value
)) {
1187 value
= PyUnicode_FromEncodedObject(value
,
1188 _ctypes_conversion_encoding
,
1189 _ctypes_conversion_errors
);
1192 } else if (!PyUnicode_Check(value
)) {
1193 PyErr_Format(PyExc_TypeError
,
1194 "unicode string expected instead of %s instance",
1195 Py_TYPE(value
)->tp_name
);
1199 if ((unsigned)PyUnicode_GET_SIZE(value
) > self
->b_size
/sizeof(wchar_t)) {
1200 PyErr_SetString(PyExc_ValueError
,
1205 result
= PyUnicode_AsWideChar((PyUnicodeObject
*)value
,
1206 (wchar_t *)self
->b_ptr
,
1207 self
->b_size
/sizeof(wchar_t));
1208 if (result
>= 0 && (size_t)result
< self
->b_size
/sizeof(wchar_t))
1209 ((wchar_t *)self
->b_ptr
)[result
] = (wchar_t)0;
1213 return result
>= 0 ? 0 : -1;
1216 static PyGetSetDef WCharArray_getsets
[] = {
1217 { "value", (getter
)WCharArray_get_value
, (setter
)WCharArray_set_value
,
1224 The next three functions copied from Python's typeobject.c.
1226 They are used to attach methods, members, or getsets to a type *after* it
1227 has been created: Arrays of characters have additional getsets to treat them
1232 add_methods(PyTypeObject *type, PyMethodDef *meth)
1234 PyObject *dict = type->tp_dict;
1235 for (; meth->ml_name != NULL; meth++) {
1237 descr = PyDescr_NewMethod(type, meth);
1240 if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0)
1248 add_members(PyTypeObject *type, PyMemberDef *memb)
1250 PyObject *dict = type->tp_dict;
1251 for (; memb->name != NULL; memb++) {
1253 descr = PyDescr_NewMember(type, memb);
1256 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1265 add_getset(PyTypeObject
*type
, PyGetSetDef
*gsp
)
1267 PyObject
*dict
= type
->tp_dict
;
1268 for (; gsp
->name
!= NULL
; gsp
++) {
1270 descr
= PyDescr_NewGetSet(type
, gsp
);
1273 if (PyDict_SetItemString(dict
, gsp
->name
, descr
) < 0)
1280 static PyCArgObject
*
1281 PyCArrayType_paramfunc(CDataObject
*self
)
1283 PyCArgObject
*p
= PyCArgObject_new();
1287 p
->pffi_type
= &ffi_type_pointer
;
1288 p
->value
.p
= (char *)self
->b_ptr
;
1290 p
->obj
= (PyObject
*)self
;
1295 PyCArrayType_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1297 PyTypeObject
*result
;
1298 StgDictObject
*stgdict
;
1299 StgDictObject
*itemdict
;
1304 Py_ssize_t itemsize
, itemalign
;
1307 typedict
= PyTuple_GetItem(args
, 2);
1311 proto
= PyDict_GetItemString(typedict
, "_length_"); /* Borrowed ref */
1312 if (!proto
|| !PyInt_Check(proto
)) {
1313 PyErr_SetString(PyExc_AttributeError
,
1314 "class must define a '_length_' attribute, "
1315 "which must be a positive integer");
1318 length
= PyInt_AS_LONG(proto
);
1320 proto
= PyDict_GetItemString(typedict
, "_type_"); /* Borrowed ref */
1322 PyErr_SetString(PyExc_AttributeError
,
1323 "class must define a '_type_' attribute");
1327 stgdict
= (StgDictObject
*)PyObject_CallObject(
1328 (PyObject
*)&PyCStgDict_Type
, NULL
);
1332 itemdict
= PyType_stgdict(proto
);
1334 PyErr_SetString(PyExc_TypeError
,
1335 "_type_ must have storage info");
1336 Py_DECREF((PyObject
*)stgdict
);
1340 assert(itemdict
->format
);
1341 if (itemdict
->format
[0] == '(') {
1342 sprintf(buf
, "(%ld,", length
);
1343 stgdict
->format
= _ctypes_alloc_format_string(buf
, itemdict
->format
+1);
1345 sprintf(buf
, "(%ld)", length
);
1346 stgdict
->format
= _ctypes_alloc_format_string(buf
, itemdict
->format
);
1348 if (stgdict
->format
== NULL
) {
1349 Py_DECREF((PyObject
*)stgdict
);
1352 stgdict
->ndim
= itemdict
->ndim
+ 1;
1353 stgdict
->shape
= PyMem_Malloc(sizeof(Py_ssize_t
*) * stgdict
->ndim
);
1354 if (stgdict
->shape
== NULL
) {
1355 Py_DECREF((PyObject
*)stgdict
);
1358 stgdict
->shape
[0] = length
;
1359 memmove(&stgdict
->shape
[1], itemdict
->shape
,
1360 sizeof(Py_ssize_t
) * (stgdict
->ndim
- 1));
1362 itemsize
= itemdict
->size
;
1363 if (length
* itemsize
< 0) {
1364 PyErr_SetString(PyExc_OverflowError
,
1369 itemalign
= itemdict
->align
;
1371 if (itemdict
->flags
& (TYPEFLAG_ISPOINTER
| TYPEFLAG_HASPOINTER
))
1372 stgdict
->flags
|= TYPEFLAG_HASPOINTER
;
1374 stgdict
->size
= itemsize
* length
;
1375 stgdict
->align
= itemalign
;
1376 stgdict
->length
= length
;
1378 stgdict
->proto
= proto
;
1380 stgdict
->paramfunc
= &PyCArrayType_paramfunc
;
1382 /* Arrays are passed as pointers to function calls. */
1383 stgdict
->ffi_type_pointer
= ffi_type_pointer
;
1385 /* create the new instance (which is a class,
1386 since we are a metatype!) */
1387 result
= (PyTypeObject
*)PyType_Type
.tp_new(type
, args
, kwds
);
1391 /* replace the class dict by our updated spam dict */
1392 if (-1 == PyDict_Update((PyObject
*)stgdict
, result
->tp_dict
)) {
1394 Py_DECREF((PyObject
*)stgdict
);
1397 Py_DECREF(result
->tp_dict
);
1398 result
->tp_dict
= (PyObject
*)stgdict
;
1400 /* Special case for character arrays.
1401 A permanent annoyance: char arrays are also strings!
1403 if (itemdict
->getfunc
== _ctypes_get_fielddesc("c")->getfunc
) {
1404 if (-1 == add_getset(result
, CharArray_getsets
))
1406 #ifdef CTYPES_UNICODE
1407 } else if (itemdict
->getfunc
== _ctypes_get_fielddesc("u")->getfunc
) {
1408 if (-1 == add_getset(result
, WCharArray_getsets
))
1413 return (PyObject
*)result
;
1416 PyTypeObject PyCArrayType_Type
= {
1417 PyVarObject_HEAD_INIT(NULL
, 0)
1418 "_ctypes.PyCArrayType", /* tp_name */
1419 0, /* tp_basicsize */
1420 0, /* tp_itemsize */
1427 0, /* tp_as_number */
1428 &CDataType_as_sequence
, /* tp_as_sequence */
1429 0, /* tp_as_mapping */
1433 0, /* tp_getattro */
1434 0, /* tp_setattro */
1435 0, /* tp_as_buffer */
1436 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
1437 "metatype for the Array Objects", /* tp_doc */
1438 0, /* tp_traverse */
1440 0, /* tp_richcompare */
1441 0, /* tp_weaklistoffset */
1443 0, /* tp_iternext */
1444 CDataType_methods
, /* tp_methods */
1449 0, /* tp_descr_get */
1450 0, /* tp_descr_set */
1451 0, /* tp_dictoffset */
1454 PyCArrayType_new
, /* tp_new */
1459 /******************************************************************/
1465 PyCSimpleType_new ensures that the new Simple_Type subclass created has a valid
1470 static char *SIMPLE_TYPE_CHARS
= "cbBhHiIlLdfuzZqQPXOv?g";
1473 c_wchar_p_from_param(PyObject
*type
, PyObject
*value
)
1475 PyObject
*as_parameter
;
1476 #if (PYTHON_API_VERSION < 1012)
1477 # error not supported
1479 if (value
== Py_None
) {
1483 if (PyUnicode_Check(value
) || PyString_Check(value
)) {
1485 struct fielddesc
*fd
= _ctypes_get_fielddesc("Z");
1487 parg
= PyCArgObject_new();
1490 parg
->pffi_type
= &ffi_type_pointer
;
1492 parg
->obj
= fd
->setfunc(&parg
->value
, value
, 0);
1493 if (parg
->obj
== NULL
) {
1497 return (PyObject
*)parg
;
1499 if (PyObject_IsInstance(value
, type
)) {
1503 if (ArrayObject_Check(value
) || PointerObject_Check(value
)) {
1504 /* c_wchar array instance or pointer(c_wchar(...)) */
1505 StgDictObject
*dt
= PyObject_stgdict(value
);
1506 StgDictObject
*dict
;
1507 assert(dt
); /* Cannot be NULL for pointer or array objects */
1508 dict
= dt
&& dt
->proto
? PyType_stgdict(dt
->proto
) : NULL
;
1509 if (dict
&& (dict
->setfunc
== _ctypes_get_fielddesc("u")->setfunc
)) {
1514 if (PyCArg_CheckExact(value
)) {
1515 /* byref(c_char(...)) */
1516 PyCArgObject
*a
= (PyCArgObject
*)value
;
1517 StgDictObject
*dict
= PyObject_stgdict(a
->obj
);
1518 if (dict
&& (dict
->setfunc
== _ctypes_get_fielddesc("u")->setfunc
)) {
1524 as_parameter
= PyObject_GetAttrString(value
, "_as_parameter_");
1526 value
= c_wchar_p_from_param(type
, as_parameter
);
1527 Py_DECREF(as_parameter
);
1530 /* XXX better message */
1531 PyErr_SetString(PyExc_TypeError
,
1537 c_char_p_from_param(PyObject
*type
, PyObject
*value
)
1539 PyObject
*as_parameter
;
1540 #if (PYTHON_API_VERSION < 1012)
1541 # error not supported
1543 if (value
== Py_None
) {
1547 if (PyString_Check(value
) || PyUnicode_Check(value
)) {
1549 struct fielddesc
*fd
= _ctypes_get_fielddesc("z");
1551 parg
= PyCArgObject_new();
1554 parg
->pffi_type
= &ffi_type_pointer
;
1556 parg
->obj
= fd
->setfunc(&parg
->value
, value
, 0);
1557 if (parg
->obj
== NULL
) {
1561 return (PyObject
*)parg
;
1563 if (PyObject_IsInstance(value
, type
)) {
1567 if (ArrayObject_Check(value
) || PointerObject_Check(value
)) {
1568 /* c_char array instance or pointer(c_char(...)) */
1569 StgDictObject
*dt
= PyObject_stgdict(value
);
1570 StgDictObject
*dict
;
1571 assert(dt
); /* Cannot be NULL for pointer or array objects */
1572 dict
= dt
&& dt
->proto
? PyType_stgdict(dt
->proto
) : NULL
;
1573 if (dict
&& (dict
->setfunc
== _ctypes_get_fielddesc("c")->setfunc
)) {
1578 if (PyCArg_CheckExact(value
)) {
1579 /* byref(c_char(...)) */
1580 PyCArgObject
*a
= (PyCArgObject
*)value
;
1581 StgDictObject
*dict
= PyObject_stgdict(a
->obj
);
1582 if (dict
&& (dict
->setfunc
== _ctypes_get_fielddesc("c")->setfunc
)) {
1588 as_parameter
= PyObject_GetAttrString(value
, "_as_parameter_");
1590 value
= c_char_p_from_param(type
, as_parameter
);
1591 Py_DECREF(as_parameter
);
1594 /* XXX better message */
1595 PyErr_SetString(PyExc_TypeError
,
1601 c_void_p_from_param(PyObject
*type
, PyObject
*value
)
1603 StgDictObject
*stgd
;
1604 PyObject
*as_parameter
;
1605 #if (PYTHON_API_VERSION < 1012)
1606 # error not supported
1610 if (value
== Py_None
) {
1614 /* Should probably allow buffer interface as well */
1616 if (PyInt_Check(value
) || PyLong_Check(value
)) {
1618 struct fielddesc
*fd
= _ctypes_get_fielddesc("P");
1620 parg
= PyCArgObject_new();
1623 parg
->pffi_type
= &ffi_type_pointer
;
1625 parg
->obj
= fd
->setfunc(&parg
->value
, value
, 0);
1626 if (parg
->obj
== NULL
) {
1630 return (PyObject
*)parg
;
1633 if (PyString_Check(value
)) {
1635 struct fielddesc
*fd
= _ctypes_get_fielddesc("z");
1637 parg
= PyCArgObject_new();
1640 parg
->pffi_type
= &ffi_type_pointer
;
1642 parg
->obj
= fd
->setfunc(&parg
->value
, value
, 0);
1643 if (parg
->obj
== NULL
) {
1647 return (PyObject
*)parg
;
1650 if (PyUnicode_Check(value
)) {
1652 struct fielddesc
*fd
= _ctypes_get_fielddesc("Z");
1654 parg
= PyCArgObject_new();
1657 parg
->pffi_type
= &ffi_type_pointer
;
1659 parg
->obj
= fd
->setfunc(&parg
->value
, value
, 0);
1660 if (parg
->obj
== NULL
) {
1664 return (PyObject
*)parg
;
1666 /* c_void_p instance (or subclass) */
1667 if (PyObject_IsInstance(value
, type
)) {
1668 /* c_void_p instances */
1672 /* ctypes array or pointer instance */
1673 if (ArrayObject_Check(value
) || PointerObject_Check(value
)) {
1674 /* Any array or pointer is accepted */
1679 if (PyCArg_CheckExact(value
)) {
1680 /* byref(c_xxx()) */
1681 PyCArgObject
*a
= (PyCArgObject
*)value
;
1682 if (a
->tag
== 'P') {
1687 /* function pointer */
1688 if (PyCFuncPtrObject_Check(value
)) {
1690 PyCFuncPtrObject
*func
;
1691 func
= (PyCFuncPtrObject
*)value
;
1692 parg
= PyCArgObject_new();
1695 parg
->pffi_type
= &ffi_type_pointer
;
1698 parg
->value
.p
= *(void **)func
->b_ptr
;
1700 return (PyObject
*)parg
;
1702 /* c_char_p, c_wchar_p */
1703 stgd
= PyObject_stgdict(value
);
1704 if (stgd
&& CDataObject_Check(value
) && stgd
->proto
&& PyString_Check(stgd
->proto
)) {
1707 switch (PyString_AS_STRING(stgd
->proto
)[0]) {
1708 case 'z': /* c_char_p */
1709 case 'Z': /* c_wchar_p */
1710 parg
= PyCArgObject_new();
1713 parg
->pffi_type
= &ffi_type_pointer
;
1717 /* Remember: b_ptr points to where the pointer is stored! */
1718 parg
->value
.p
= *(void **)(((CDataObject
*)value
)->b_ptr
);
1719 return (PyObject
*)parg
;
1723 as_parameter
= PyObject_GetAttrString(value
, "_as_parameter_");
1725 value
= c_void_p_from_param(type
, as_parameter
);
1726 Py_DECREF(as_parameter
);
1729 /* XXX better message */
1730 PyErr_SetString(PyExc_TypeError
,
1734 #if (PYTHON_API_VERSION >= 1012)
1736 static PyMethodDef c_void_p_method
= { "from_param", c_void_p_from_param
, METH_O
};
1737 static PyMethodDef c_char_p_method
= { "from_param", c_char_p_from_param
, METH_O
};
1738 static PyMethodDef c_wchar_p_method
= { "from_param", c_wchar_p_from_param
, METH_O
};
1742 static PyMethodDef c_void_p_method
= { "from_param", c_void_p_from_param
, METH_VARARGS
};
1743 static PyMethodDef c_char_p_method
= { "from_param", c_char_p_from_param
, METH_VARARGS
};
1744 static PyMethodDef c_wchar_p_method
= { "from_param", c_wchar_p_from_param
, METH_VARARGS
};
1748 static PyObject
*CreateSwappedType(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
,
1749 PyObject
*proto
, struct fielddesc
*fmt
)
1751 PyTypeObject
*result
;
1752 StgDictObject
*stgdict
;
1753 PyObject
*name
= PyTuple_GET_ITEM(args
, 0);
1754 PyObject
*swapped_args
;
1755 static PyObject
*suffix
;
1758 swapped_args
= PyTuple_New(PyTuple_GET_SIZE(args
));
1763 #ifdef WORDS_BIGENDIAN
1764 suffix
= PyString_InternFromString("_le");
1766 suffix
= PyString_InternFromString("_be");
1770 PyString_Concat(&name
, suffix
);
1774 PyTuple_SET_ITEM(swapped_args
, 0, name
);
1775 for (i
=1; i
<PyTuple_GET_SIZE(args
); ++i
) {
1776 PyObject
*v
= PyTuple_GET_ITEM(args
, i
);
1778 PyTuple_SET_ITEM(swapped_args
, i
, v
);
1781 /* create the new instance (which is a class,
1782 since we are a metatype!) */
1783 result
= (PyTypeObject
*)PyType_Type
.tp_new(type
, swapped_args
, kwds
);
1784 Py_DECREF(swapped_args
);
1788 stgdict
= (StgDictObject
*)PyObject_CallObject(
1789 (PyObject
*)&PyCStgDict_Type
, NULL
);
1790 if (!stgdict
) /* XXX leaks result! */
1793 stgdict
->ffi_type_pointer
= *fmt
->pffi_type
;
1794 stgdict
->align
= fmt
->pffi_type
->alignment
;
1795 stgdict
->length
= 0;
1796 stgdict
->size
= fmt
->pffi_type
->size
;
1797 stgdict
->setfunc
= fmt
->setfunc_swapped
;
1798 stgdict
->getfunc
= fmt
->getfunc_swapped
;
1801 stgdict
->proto
= proto
;
1803 /* replace the class dict by our updated spam dict */
1804 if (-1 == PyDict_Update((PyObject
*)stgdict
, result
->tp_dict
)) {
1806 Py_DECREF((PyObject
*)stgdict
);
1809 Py_DECREF(result
->tp_dict
);
1810 result
->tp_dict
= (PyObject
*)stgdict
;
1812 return (PyObject
*)result
;
1815 static PyCArgObject
*
1816 PyCSimpleType_paramfunc(CDataObject
*self
)
1818 StgDictObject
*dict
;
1821 struct fielddesc
*fd
;
1823 dict
= PyObject_stgdict((PyObject
*)self
);
1824 assert(dict
); /* Cannot be NULL for CDataObject instances */
1825 fmt
= PyString_AsString(dict
->proto
);
1828 fd
= _ctypes_get_fielddesc(fmt
);
1831 parg
= PyCArgObject_new();
1836 parg
->pffi_type
= fd
->pffi_type
;
1838 parg
->obj
= (PyObject
*)self
;
1839 memcpy(&parg
->value
, self
->b_ptr
, self
->b_size
);
1844 PyCSimpleType_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1846 PyTypeObject
*result
;
1847 StgDictObject
*stgdict
;
1849 const char *proto_str
;
1850 Py_ssize_t proto_len
;
1852 struct fielddesc
*fmt
;
1854 /* create the new instance (which is a class,
1855 since we are a metatype!) */
1856 result
= (PyTypeObject
*)PyType_Type
.tp_new(type
, args
, kwds
);
1860 proto
= PyObject_GetAttrString((PyObject
*)result
, "_type_"); /* new ref */
1862 PyErr_SetString(PyExc_AttributeError
,
1863 "class must define a '_type_' attribute");
1869 if (PyString_Check(proto
)) {
1870 proto_str
= PyString_AS_STRING(proto
);
1871 proto_len
= PyString_GET_SIZE(proto
);
1873 PyErr_SetString(PyExc_TypeError
,
1874 "class must define a '_type_' string attribute");
1877 if (proto_len
!= 1) {
1878 PyErr_SetString(PyExc_ValueError
,
1879 "class must define a '_type_' attribute "
1880 "which must be a string of length 1");
1883 if (!strchr(SIMPLE_TYPE_CHARS
, *proto_str
)) {
1884 PyErr_Format(PyExc_AttributeError
,
1885 "class must define a '_type_' attribute which must be\n"
1886 "a single character string containing one of '%s'.",
1890 fmt
= _ctypes_get_fielddesc(PyString_AS_STRING(proto
));
1892 PyErr_Format(PyExc_ValueError
,
1893 "_type_ '%s' not supported",
1894 PyString_AS_STRING(proto
));
1898 stgdict
= (StgDictObject
*)PyObject_CallObject(
1899 (PyObject
*)&PyCStgDict_Type
, NULL
);
1903 stgdict
->ffi_type_pointer
= *fmt
->pffi_type
;
1904 stgdict
->align
= fmt
->pffi_type
->alignment
;
1905 stgdict
->length
= 0;
1906 stgdict
->size
= fmt
->pffi_type
->size
;
1907 stgdict
->setfunc
= fmt
->setfunc
;
1908 stgdict
->getfunc
= fmt
->getfunc
;
1909 #ifdef WORDS_BIGENDIAN
1910 stgdict
->format
= _ctypes_alloc_format_string(">", proto_str
);
1912 stgdict
->format
= _ctypes_alloc_format_string("<", proto_str
);
1914 if (stgdict
->format
== NULL
) {
1917 Py_DECREF((PyObject
*)stgdict
);
1921 stgdict
->paramfunc
= PyCSimpleType_paramfunc
;
1923 if (result->tp_base != &Simple_Type) {
1924 stgdict->setfunc = NULL;
1925 stgdict->getfunc = NULL;
1929 /* This consumes the refcount on proto which we have */
1930 stgdict
->proto
= proto
;
1932 /* replace the class dict by our updated spam dict */
1933 if (-1 == PyDict_Update((PyObject
*)stgdict
, result
->tp_dict
)) {
1935 Py_DECREF((PyObject
*)stgdict
);
1938 Py_DECREF(result
->tp_dict
);
1939 result
->tp_dict
= (PyObject
*)stgdict
;
1941 /* Install from_param class methods in ctypes base classes.
1942 Overrides the PyCSimpleType_from_param generic method.
1944 if (result
->tp_base
== &Simple_Type
) {
1945 switch (PyString_AS_STRING(proto
)[0]) {
1946 case 'z': /* c_char_p */
1947 ml
= &c_char_p_method
;
1948 stgdict
->flags
|= TYPEFLAG_ISPOINTER
;
1950 case 'Z': /* c_wchar_p */
1951 ml
= &c_wchar_p_method
;
1952 stgdict
->flags
|= TYPEFLAG_ISPOINTER
;
1954 case 'P': /* c_void_p */
1955 ml
= &c_void_p_method
;
1956 stgdict
->flags
|= TYPEFLAG_ISPOINTER
;
1962 stgdict
->flags
|= TYPEFLAG_ISPOINTER
;
1970 #if (PYTHON_API_VERSION >= 1012)
1973 meth
= PyDescr_NewClassMethod(result
, ml
);
1978 PyObject
*meth
, *func
;
1980 func
= PyCFunction_New(ml
, NULL
);
1983 meth
= PyObject_CallFunctionObjArgs(
1984 (PyObject
*)&PyClassMethod_Type
,
1991 x
= PyDict_SetItemString(result
->tp_dict
,
2002 if (type
== &PyCSimpleType_Type
&& fmt
->setfunc_swapped
&& fmt
->getfunc_swapped
) {
2003 PyObject
*swapped
= CreateSwappedType(type
, args
, kwds
,
2005 StgDictObject
*sw_dict
;
2006 if (swapped
== NULL
) {
2010 sw_dict
= PyType_stgdict(swapped
);
2011 #ifdef WORDS_BIGENDIAN
2012 PyObject_SetAttrString((PyObject
*)result
, "__ctype_le__", swapped
);
2013 PyObject_SetAttrString((PyObject
*)result
, "__ctype_be__", (PyObject
*)result
);
2014 PyObject_SetAttrString(swapped
, "__ctype_be__", (PyObject
*)result
);
2015 PyObject_SetAttrString(swapped
, "__ctype_le__", swapped
);
2016 /* We are creating the type for the OTHER endian */
2017 sw_dict
->format
= _ctypes_alloc_format_string("<", stgdict
->format
+1);
2019 PyObject_SetAttrString((PyObject
*)result
, "__ctype_be__", swapped
);
2020 PyObject_SetAttrString((PyObject
*)result
, "__ctype_le__", (PyObject
*)result
);
2021 PyObject_SetAttrString(swapped
, "__ctype_le__", (PyObject
*)result
);
2022 PyObject_SetAttrString(swapped
, "__ctype_be__", swapped
);
2023 /* We are creating the type for the OTHER endian */
2024 sw_dict
->format
= _ctypes_alloc_format_string(">", stgdict
->format
+1);
2027 if (PyErr_Occurred()) {
2033 return (PyObject
*)result
;
2037 * This is a *class method*.
2038 * Convert a parameter into something that ConvParam can handle.
2041 PyCSimpleType_from_param(PyObject
*type
, PyObject
*value
)
2043 StgDictObject
*dict
;
2046 struct fielddesc
*fd
;
2047 PyObject
*as_parameter
;
2049 /* If the value is already an instance of the requested type,
2050 we can use it as is */
2051 if (1 == PyObject_IsInstance(value
, type
)) {
2056 dict
= PyType_stgdict(type
);
2059 /* I think we can rely on this being a one-character string */
2060 fmt
= PyString_AsString(dict
->proto
);
2063 fd
= _ctypes_get_fielddesc(fmt
);
2066 parg
= PyCArgObject_new();
2071 parg
->pffi_type
= fd
->pffi_type
;
2072 parg
->obj
= fd
->setfunc(&parg
->value
, value
, 0);
2074 return (PyObject
*)parg
;
2078 as_parameter
= PyObject_GetAttrString(value
, "_as_parameter_");
2080 value
= PyCSimpleType_from_param(type
, as_parameter
);
2081 Py_DECREF(as_parameter
);
2084 PyErr_SetString(PyExc_TypeError
,
2089 static PyMethodDef PyCSimpleType_methods
[] = {
2090 { "from_param", PyCSimpleType_from_param
, METH_O
, from_param_doc
},
2091 { "from_address", CDataType_from_address
, METH_O
, from_address_doc
},
2092 { "from_buffer", CDataType_from_buffer
, METH_VARARGS
, from_buffer_doc
, },
2093 { "from_buffer_copy", CDataType_from_buffer_copy
, METH_VARARGS
, from_buffer_copy_doc
, },
2094 { "in_dll", CDataType_in_dll
, METH_VARARGS
, in_dll_doc
},
2098 PyTypeObject PyCSimpleType_Type
= {
2099 PyVarObject_HEAD_INIT(NULL
, 0)
2100 "_ctypes.PyCSimpleType", /* tp_name */
2101 0, /* tp_basicsize */
2102 0, /* tp_itemsize */
2109 0, /* tp_as_number */
2110 &CDataType_as_sequence
, /* tp_as_sequence */
2111 0, /* tp_as_mapping */
2115 0, /* tp_getattro */
2116 0, /* tp_setattro */
2117 0, /* tp_as_buffer */
2118 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
2119 "metatype for the PyCSimpleType Objects", /* tp_doc */
2120 0, /* tp_traverse */
2122 0, /* tp_richcompare */
2123 0, /* tp_weaklistoffset */
2125 0, /* tp_iternext */
2126 PyCSimpleType_methods
, /* tp_methods */
2131 0, /* tp_descr_get */
2132 0, /* tp_descr_set */
2133 0, /* tp_dictoffset */
2136 PyCSimpleType_new
, /* tp_new */
2140 /******************************************************************/
2146 converters_from_argtypes(PyObject
*ob
)
2148 PyObject
*converters
;
2152 ob
= PySequence_Tuple(ob
); /* new reference */
2154 PyErr_SetString(PyExc_TypeError
,
2155 "_argtypes_ must be a sequence of types");
2159 nArgs
= PyTuple_GET_SIZE(ob
);
2160 converters
= PyTuple_New(nArgs
);
2164 /* I have to check if this is correct. Using c_char, which has a size
2165 of 1, will be assumed to be pushed as only one byte!
2166 Aren't these promoted to integers by the C compiler and pushed as 4 bytes?
2169 for (i
= 0; i
< nArgs
; ++i
) {
2170 PyObject
*tp
= PyTuple_GET_ITEM(ob
, i
);
2171 PyObject
*cnv
= PyObject_GetAttrString(tp
, "from_param");
2173 goto argtypes_error_1
;
2174 PyTuple_SET_ITEM(converters
, i
, cnv
);
2180 Py_XDECREF(converters
);
2182 PyErr_Format(PyExc_TypeError
,
2183 #if (PY_VERSION_HEX < 0x02050000)
2184 "item %d in _argtypes_ has no from_param method",
2186 "item %zd in _argtypes_ has no from_param method",
2193 make_funcptrtype_dict(StgDictObject
*stgdict
)
2196 PyObject
*converters
= NULL
;
2198 stgdict
->align
= _ctypes_get_fielddesc("P")->pffi_type
->alignment
;
2199 stgdict
->length
= 1;
2200 stgdict
->size
= sizeof(void *);
2201 stgdict
->setfunc
= NULL
;
2202 stgdict
->getfunc
= NULL
;
2203 stgdict
->ffi_type_pointer
= ffi_type_pointer
;
2205 ob
= PyDict_GetItemString((PyObject
*)stgdict
, "_flags_");
2206 if (!ob
|| !PyInt_Check(ob
)) {
2207 PyErr_SetString(PyExc_TypeError
,
2208 "class must define _flags_ which must be an integer");
2211 stgdict
->flags
= PyInt_AS_LONG(ob
) | TYPEFLAG_ISPOINTER
;
2213 /* _argtypes_ is optional... */
2214 ob
= PyDict_GetItemString((PyObject
*)stgdict
, "_argtypes_");
2216 converters
= converters_from_argtypes(ob
);
2220 stgdict
->argtypes
= ob
;
2221 stgdict
->converters
= converters
;
2224 ob
= PyDict_GetItemString((PyObject
*)stgdict
, "_restype_");
2226 if (ob
!= Py_None
&& !PyType_stgdict(ob
) && !PyCallable_Check(ob
)) {
2227 PyErr_SetString(PyExc_TypeError
,
2228 "_restype_ must be a type, a callable, or None");
2232 stgdict
->restype
= ob
;
2233 stgdict
->checker
= PyObject_GetAttrString(ob
, "_check_retval_");
2234 if (stgdict
->checker
== NULL
)
2237 /* XXX later, maybe.
2238 ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_");
2240 if (!PyCallable_Check(ob)) {
2241 PyErr_SetString(PyExc_TypeError,
2242 "_errcheck_ must be callable");
2246 stgdict->errcheck = ob;
2252 Py_XDECREF(converters
);
2257 static PyCArgObject
*
2258 PyCFuncPtrType_paramfunc(CDataObject
*self
)
2262 parg
= PyCArgObject_new();
2267 parg
->pffi_type
= &ffi_type_pointer
;
2269 parg
->obj
= (PyObject
*)self
;
2270 parg
->value
.p
= *(void **)self
->b_ptr
;
2275 PyCFuncPtrType_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2277 PyTypeObject
*result
;
2278 StgDictObject
*stgdict
;
2280 stgdict
= (StgDictObject
*)PyObject_CallObject(
2281 (PyObject
*)&PyCStgDict_Type
, NULL
);
2285 stgdict
->paramfunc
= PyCFuncPtrType_paramfunc
;
2286 /* We do NOT expose the function signature in the format string. It
2287 is impossible, generally, because the only requirement for the
2288 argtypes items is that they have a .from_param method - we do not
2289 know the types of the arguments (although, in practice, most
2290 argtypes would be a ctypes type).
2292 stgdict
->format
= _ctypes_alloc_format_string(NULL
, "X{}");
2293 stgdict
->flags
|= TYPEFLAG_ISPOINTER
;
2295 /* create the new instance (which is a class,
2296 since we are a metatype!) */
2297 result
= (PyTypeObject
*)PyType_Type
.tp_new(type
, args
, kwds
);
2298 if (result
== NULL
) {
2299 Py_DECREF((PyObject
*)stgdict
);
2303 /* replace the class dict by our updated storage dict */
2304 if (-1 == PyDict_Update((PyObject
*)stgdict
, result
->tp_dict
)) {
2306 Py_DECREF((PyObject
*)stgdict
);
2309 Py_DECREF(result
->tp_dict
);
2310 result
->tp_dict
= (PyObject
*)stgdict
;
2312 if (-1 == make_funcptrtype_dict(stgdict
)) {
2317 return (PyObject
*)result
;
2320 PyTypeObject PyCFuncPtrType_Type
= {
2321 PyVarObject_HEAD_INIT(NULL
, 0)
2322 "_ctypes.PyCFuncPtrType", /* tp_name */
2323 0, /* tp_basicsize */
2324 0, /* tp_itemsize */
2331 0, /* tp_as_number */
2332 &CDataType_as_sequence
, /* tp_as_sequence */
2333 0, /* tp_as_mapping */
2337 0, /* tp_getattro */
2338 0, /* tp_setattro */
2339 0, /* tp_as_buffer */
2340 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
, /* tp_flags */
2341 "metatype for C function pointers", /* tp_doc */
2342 (traverseproc
)CDataType_traverse
, /* tp_traverse */
2343 (inquiry
)CDataType_clear
, /* tp_clear */
2344 0, /* tp_richcompare */
2345 0, /* tp_weaklistoffset */
2347 0, /* tp_iternext */
2348 CDataType_methods
, /* tp_methods */
2353 0, /* tp_descr_get */
2354 0, /* tp_descr_set */
2355 0, /* tp_dictoffset */
2358 PyCFuncPtrType_new
, /* tp_new */
2363 /*****************************************************************
2364 * Code to keep needed objects alive
2367 static CDataObject
*
2368 PyCData_GetContainer(CDataObject
*self
)
2370 while (self
->b_base
)
2371 self
= self
->b_base
;
2372 if (self
->b_objects
== NULL
) {
2373 if (self
->b_length
) {
2374 self
->b_objects
= PyDict_New();
2377 self
->b_objects
= Py_None
;
2384 GetKeepedObjects(CDataObject
*target
)
2386 return PyCData_GetContainer(target
)->b_objects
;
2390 unique_key(CDataObject
*target
, Py_ssize_t index
)
2396 assert(sizeof(string
) - 1 > sizeof(Py_ssize_t
) * 2);
2397 #if (PY_VERSION_HEX < 0x02050000)
2398 cp
+= sprintf(cp
, "%x", index
);
2400 cp
+= sprintf(cp
, "%x", Py_SAFE_DOWNCAST(index
, Py_ssize_t
, int));
2402 while (target
->b_base
) {
2403 bytes_left
= sizeof(string
) - (cp
- string
) - 1;
2404 /* Hex format needs 2 characters per byte */
2405 if (bytes_left
< sizeof(Py_ssize_t
) * 2) {
2406 PyErr_SetString(PyExc_ValueError
,
2407 "ctypes object structure too deep");
2410 #if (PY_VERSION_HEX < 0x02050000)
2411 cp
+= sprintf(cp
, ":%x", (int)target
->b_index
);
2413 cp
+= sprintf(cp
, ":%x", Py_SAFE_DOWNCAST(target
->b_index
, Py_ssize_t
, int));
2415 target
= target
->b_base
;
2417 return PyString_FromStringAndSize(string
, cp
-string
);
2421 * Keep a reference to 'keep' in the 'target', at index 'index'.
2423 * If 'keep' is None, do nothing.
2425 * Otherwise create a dictionary (if it does not yet exist) id the root
2426 * objects 'b_objects' item, which will store the 'keep' object under a unique
2429 * The unique_key helper travels the target's b_base pointer down to the root,
2430 * building a string containing hex-formatted indexes found during traversal,
2431 * separated by colons.
2433 * The index tuple is used as a key into the root object's b_objects dict.
2435 * Note: This function steals a refcount of the third argument, even if it
2439 KeepRef(CDataObject
*target
, Py_ssize_t index
, PyObject
*keep
)
2445 /* Optimization: no need to store None */
2446 if (keep
== Py_None
) {
2450 ob
= PyCData_GetContainer(target
);
2451 if (ob
->b_objects
== NULL
|| !PyDict_CheckExact(ob
->b_objects
)) {
2452 Py_XDECREF(ob
->b_objects
);
2453 ob
->b_objects
= keep
; /* refcount consumed */
2456 key
= unique_key(target
, index
);
2461 result
= PyDict_SetItem(ob
->b_objects
, key
, keep
);
2467 /******************************************************************/
2472 PyCData_traverse(CDataObject
*self
, visitproc visit
, void *arg
)
2474 Py_VISIT(self
->b_objects
);
2475 Py_VISIT((PyObject
*)self
->b_base
);
2480 PyCData_clear(CDataObject
*self
)
2482 StgDictObject
*dict
= PyObject_stgdict((PyObject
*)self
);
2483 assert(dict
); /* Cannot be NULL for CDataObject instances */
2484 Py_CLEAR(self
->b_objects
);
2485 if ((self
->b_needsfree
)
2486 && ((size_t)dict
->size
> sizeof(self
->b_value
)))
2487 PyMem_Free(self
->b_ptr
);
2489 Py_CLEAR(self
->b_base
);
2494 PyCData_dealloc(PyObject
*self
)
2496 PyCData_clear((CDataObject
*)self
);
2497 Py_TYPE(self
)->tp_free(self
);
2500 static PyMemberDef PyCData_members
[] = {
2501 { "_b_base_", T_OBJECT
,
2502 offsetof(CDataObject
, b_base
), READONLY
,
2503 "the base object" },
2504 { "_b_needsfree_", T_INT
,
2505 offsetof(CDataObject
, b_needsfree
), READONLY
,
2506 "whether the object owns the memory or not" },
2507 { "_objects", T_OBJECT
,
2508 offsetof(CDataObject
, b_objects
), READONLY
,
2509 "internal objects tree (NEVER CHANGE THIS OBJECT!)"},
2513 #if (PY_VERSION_HEX >= 0x02060000)
2514 static int PyCData_NewGetBuffer(PyObject
*_self
, Py_buffer
*view
, int flags
)
2516 CDataObject
*self
= (CDataObject
*)_self
;
2517 StgDictObject
*dict
= PyObject_stgdict(_self
);
2520 if (view
== NULL
) return 0;
2522 view
->buf
= self
->b_ptr
;
2525 view
->len
= self
->b_size
;
2527 /* use default format character if not set */
2528 view
->format
= dict
->format
? dict
->format
: "B";
2529 view
->ndim
= dict
->ndim
;
2530 view
->shape
= dict
->shape
;
2531 view
->itemsize
= self
->b_size
;
2532 for (i
= 0; i
< view
->ndim
; ++i
) {
2533 view
->itemsize
/= dict
->shape
[i
];
2535 view
->strides
= NULL
;
2536 view
->suboffsets
= NULL
;
2537 view
->internal
= NULL
;
2542 static Py_ssize_t
PyCData_GetSegcount(PyObject
*_self
, Py_ssize_t
*lenp
)
2549 static Py_ssize_t
PyCData_GetBuffer(PyObject
*_self
, Py_ssize_t seg
, void **pptr
)
2551 CDataObject
*self
= (CDataObject
*)_self
;
2553 /* Hm. Must this set an exception? */
2556 *pptr
= self
->b_ptr
;
2557 return self
->b_size
;
2560 static PyBufferProcs PyCData_as_buffer
= {
2561 (readbufferproc
)PyCData_GetBuffer
,
2562 (writebufferproc
)PyCData_GetBuffer
,
2563 (segcountproc
)PyCData_GetSegcount
,
2564 (charbufferproc
)NULL
,
2565 #if (PY_VERSION_HEX >= 0x02060000)
2566 (getbufferproc
)PyCData_NewGetBuffer
,
2567 (releasebufferproc
)NULL
,
2572 * CData objects are mutable, so they cannot be hashable!
2575 PyCData_nohash(PyObject
*self
)
2577 PyErr_SetString(PyExc_TypeError
, "unhashable type");
2582 PyCData_reduce(PyObject
*_self
, PyObject
*args
)
2584 CDataObject
*self
= (CDataObject
*)_self
;
2586 if (PyObject_stgdict(_self
)->flags
& (TYPEFLAG_ISPOINTER
|TYPEFLAG_HASPOINTER
)) {
2587 PyErr_SetString(PyExc_ValueError
,
2588 "ctypes objects containing pointers cannot be pickled");
2591 return Py_BuildValue("O(O(NN))",
2594 PyObject_GetAttrString(_self
, "__dict__"),
2595 PyString_FromStringAndSize(self
->b_ptr
, self
->b_size
));
2599 PyCData_setstate(PyObject
*_self
, PyObject
*args
)
2604 PyObject
*dict
, *mydict
;
2605 CDataObject
*self
= (CDataObject
*)_self
;
2606 if (!PyArg_ParseTuple(args
, "Os#", &dict
, &data
, &len
))
2608 if (len
> self
->b_size
)
2610 memmove(self
->b_ptr
, data
, len
);
2611 mydict
= PyObject_GetAttrString(_self
, "__dict__");
2612 res
= PyDict_Update(mydict
, dict
);
2621 * default __ctypes_from_outparam__ method returns self.
2624 PyCData_from_outparam(PyObject
*self
, PyObject
*args
)
2630 static PyMethodDef PyCData_methods
[] = {
2631 { "__ctypes_from_outparam__", PyCData_from_outparam
, METH_NOARGS
, },
2632 { "__reduce__", PyCData_reduce
, METH_NOARGS
, },
2633 { "__setstate__", PyCData_setstate
, METH_VARARGS
, },
2637 PyTypeObject PyCData_Type
= {
2638 PyVarObject_HEAD_INIT(NULL
, 0)
2640 sizeof(CDataObject
), /* tp_basicsize */
2641 0, /* tp_itemsize */
2642 PyCData_dealloc
, /* tp_dealloc */
2648 0, /* tp_as_number */
2649 0, /* tp_as_sequence */
2650 0, /* tp_as_mapping */
2651 PyCData_nohash
, /* tp_hash */
2654 0, /* tp_getattro */
2655 0, /* tp_setattro */
2656 &PyCData_as_buffer
, /* tp_as_buffer */
2657 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_NEWBUFFER
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
2658 "XXX to be provided", /* tp_doc */
2659 (traverseproc
)PyCData_traverse
, /* tp_traverse */
2660 (inquiry
)PyCData_clear
, /* tp_clear */
2661 0, /* tp_richcompare */
2662 0, /* tp_weaklistoffset */
2664 0, /* tp_iternext */
2665 PyCData_methods
, /* tp_methods */
2666 PyCData_members
, /* tp_members */
2670 0, /* tp_descr_get */
2671 0, /* tp_descr_set */
2672 0, /* tp_dictoffset */
2679 static int PyCData_MallocBuffer(CDataObject
*obj
, StgDictObject
*dict
)
2681 if ((size_t)dict
->size
<= sizeof(obj
->b_value
)) {
2682 /* No need to call malloc, can use the default buffer */
2683 obj
->b_ptr
= (char *)&obj
->b_value
;
2684 /* The b_needsfree flag does not mean that we actually did
2685 call PyMem_Malloc to allocate the memory block; instead it
2686 means we are the *owner* of the memory and are responsible
2687 for freeing resources associated with the memory. This is
2688 also the reason that b_needsfree is exposed to Python.
2690 obj
->b_needsfree
= 1;
2692 /* In python 2.4, and ctypes 0.9.6, the malloc call took about
2693 33% of the creation time for c_int().
2695 obj
->b_ptr
= (char *)PyMem_Malloc(dict
->size
);
2696 if (obj
->b_ptr
== NULL
) {
2700 obj
->b_needsfree
= 1;
2701 memset(obj
->b_ptr
, 0, dict
->size
);
2703 obj
->b_size
= dict
->size
;
2708 PyCData_FromBaseObj(PyObject
*type
, PyObject
*base
, Py_ssize_t index
, char *adr
)
2711 StgDictObject
*dict
;
2713 assert(PyType_Check(type
));
2714 dict
= PyType_stgdict(type
);
2716 PyErr_SetString(PyExc_TypeError
,
2720 dict
->flags
|= DICTFLAG_FINAL
;
2721 cmem
= (CDataObject
*)((PyTypeObject
*)type
)->tp_alloc((PyTypeObject
*)type
, 0);
2724 assert(CDataObject_Check(cmem
));
2726 cmem
->b_length
= dict
->length
;
2727 cmem
->b_size
= dict
->size
;
2728 if (base
) { /* use base's buffer */
2729 assert(CDataObject_Check(base
));
2731 cmem
->b_needsfree
= 0;
2733 cmem
->b_base
= (CDataObject
*)base
;
2734 cmem
->b_index
= index
;
2735 } else { /* copy contents of adr */
2736 if (-1 == PyCData_MallocBuffer(cmem
, dict
)) {
2740 memcpy(cmem
->b_ptr
, adr
, dict
->size
);
2741 cmem
->b_index
= index
;
2743 return (PyObject
*)cmem
;
2747 Box a memory block into a CData instance.
2750 PyCData_AtAddress(PyObject
*type
, void *buf
)
2753 StgDictObject
*dict
;
2755 assert(PyType_Check(type
));
2756 dict
= PyType_stgdict(type
);
2758 PyErr_SetString(PyExc_TypeError
,
2762 dict
->flags
|= DICTFLAG_FINAL
;
2764 pd
= (CDataObject
*)((PyTypeObject
*)type
)->tp_alloc((PyTypeObject
*)type
, 0);
2767 assert(CDataObject_Check(pd
));
2768 pd
->b_ptr
= (char *)buf
;
2769 pd
->b_length
= dict
->length
;
2770 pd
->b_size
= dict
->size
;
2771 return (PyObject
*)pd
;
2775 This function returns TRUE for c_int, c_void_p, and these kind of
2776 classes. FALSE otherwise FALSE also for subclasses of c_int and
2779 int _ctypes_simple_instance(PyObject
*obj
)
2781 PyTypeObject
*type
= (PyTypeObject
*)obj
;
2783 if (PyCSimpleTypeObject_Check(type
))
2784 return type
->tp_base
!= &Simple_Type
;
2789 PyCData_get(PyObject
*type
, GETFUNC getfunc
, PyObject
*src
,
2790 Py_ssize_t index
, Py_ssize_t size
, char *adr
)
2792 StgDictObject
*dict
;
2794 return getfunc(adr
, size
);
2796 dict
= PyType_stgdict(type
);
2797 if (dict
&& dict
->getfunc
&& !_ctypes_simple_instance(type
))
2798 return dict
->getfunc(adr
, size
);
2799 return PyCData_FromBaseObj(type
, src
, index
, adr
);
2803 Helper function for PyCData_set below.
2806 _PyCData_set(CDataObject
*dst
, PyObject
*type
, SETFUNC setfunc
, PyObject
*value
,
2807 Py_ssize_t size
, char *ptr
)
2812 return setfunc(ptr
, value
, size
);
2814 if (!CDataObject_Check(value
)) {
2815 StgDictObject
*dict
= PyType_stgdict(type
);
2816 if (dict
&& dict
->setfunc
)
2817 return dict
->setfunc(ptr
, value
, size
);
2819 If value is a tuple, we try to call the type with the tuple
2822 assert(PyType_Check(type
));
2823 if (PyTuple_Check(value
)) {
2826 ob
= PyObject_CallObject(type
, value
);
2828 _ctypes_extend_error(PyExc_RuntimeError
, "(%s) ",
2829 ((PyTypeObject
*)type
)->tp_name
);
2832 result
= _PyCData_set(dst
, type
, setfunc
, ob
,
2836 } else if (value
== Py_None
&& PyCPointerTypeObject_Check(type
)) {
2837 *(void **)ptr
= NULL
;
2841 PyErr_Format(PyExc_TypeError
,
2842 "expected %s instance, got %s",
2843 ((PyTypeObject
*)type
)->tp_name
,
2844 Py_TYPE(value
)->tp_name
);
2848 src
= (CDataObject
*)value
;
2850 if (PyObject_IsInstance(value
, type
)) {
2855 if (PyCPointerTypeObject_Check(type
))
2858 value
= GetKeepedObjects(src
);
2863 if (PyCPointerTypeObject_Check(type
)
2864 && ArrayObject_Check(value
)) {
2865 StgDictObject
*p1
, *p2
;
2867 p1
= PyObject_stgdict(value
);
2868 assert(p1
); /* Cannot be NULL for array instances */
2869 p2
= PyType_stgdict(type
);
2870 assert(p2
); /* Cannot be NULL for pointer types */
2872 if (p1
->proto
!= p2
->proto
) {
2873 PyErr_Format(PyExc_TypeError
,
2874 "incompatible types, %s instance instead of %s instance",
2875 Py_TYPE(value
)->tp_name
,
2876 ((PyTypeObject
*)type
)->tp_name
);
2879 *(void **)ptr
= src
->b_ptr
;
2881 keep
= GetKeepedObjects(src
);
2883 We are assigning an array object to a field which represents
2884 a pointer. This has the same effect as converting an array
2885 into a pointer. So, again, we have to keep the whole object
2886 pointed to (which is the array in this case) alive, and not
2887 only it's object list. So we create a tuple, containing
2888 b_objects list PLUS the array itself, and return that!
2890 return PyTuple_Pack(2, keep
, value
);
2892 PyErr_Format(PyExc_TypeError
,
2893 "incompatible types, %s instance instead of %s instance",
2894 Py_TYPE(value
)->tp_name
,
2895 ((PyTypeObject
*)type
)->tp_name
);
2900 * Set a slice in object 'dst', which has the type 'type',
2901 * to the value 'value'.
2904 PyCData_set(PyObject
*dst
, PyObject
*type
, SETFUNC setfunc
, PyObject
*value
,
2905 Py_ssize_t index
, Py_ssize_t size
, char *ptr
)
2907 CDataObject
*mem
= (CDataObject
*)dst
;
2910 if (!CDataObject_Check(dst
)) {
2911 PyErr_SetString(PyExc_TypeError
,
2912 "not a ctype instance");
2916 result
= _PyCData_set(mem
, type
, setfunc
, value
,
2921 /* KeepRef steals a refcount from it's last argument */
2922 /* If KeepRef fails, we are stumped. The dst memory block has already
2924 return KeepRef(mem
, index
, result
);
2928 /******************************************************************/
2930 GenericPyCData_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2933 StgDictObject
*dict
;
2935 dict
= PyType_stgdict((PyObject
*)type
);
2937 PyErr_SetString(PyExc_TypeError
,
2941 dict
->flags
|= DICTFLAG_FINAL
;
2943 obj
= (CDataObject
*)type
->tp_alloc(type
, 0);
2949 obj
->b_objects
= NULL
;
2950 obj
->b_length
= dict
->length
;
2952 if (-1 == PyCData_MallocBuffer(obj
, dict
)) {
2956 return (PyObject
*)obj
;
2958 /*****************************************************************/
2964 PyCFuncPtr_set_errcheck(PyCFuncPtrObject
*self
, PyObject
*ob
)
2966 if (ob
&& !PyCallable_Check(ob
)) {
2967 PyErr_SetString(PyExc_TypeError
,
2968 "the errcheck attribute must be callable");
2971 Py_XDECREF(self
->errcheck
);
2973 self
->errcheck
= ob
;
2978 PyCFuncPtr_get_errcheck(PyCFuncPtrObject
*self
)
2980 if (self
->errcheck
) {
2981 Py_INCREF(self
->errcheck
);
2982 return self
->errcheck
;
2989 PyCFuncPtr_set_restype(PyCFuncPtrObject
*self
, PyObject
*ob
)
2992 Py_XDECREF(self
->restype
);
2993 self
->restype
= NULL
;
2994 Py_XDECREF(self
->checker
);
2995 self
->checker
= NULL
;
2998 if (ob
!= Py_None
&& !PyType_stgdict(ob
) && !PyCallable_Check(ob
)) {
2999 PyErr_SetString(PyExc_TypeError
,
3000 "restype must be a type, a callable, or None");
3003 Py_XDECREF(self
->checker
);
3004 Py_XDECREF(self
->restype
);
3007 self
->checker
= PyObject_GetAttrString(ob
, "_check_retval_");
3008 if (self
->checker
== NULL
)
3014 PyCFuncPtr_get_restype(PyCFuncPtrObject
*self
)
3016 StgDictObject
*dict
;
3017 if (self
->restype
) {
3018 Py_INCREF(self
->restype
);
3019 return self
->restype
;
3021 dict
= PyObject_stgdict((PyObject
*)self
);
3022 assert(dict
); /* Cannot be NULL for PyCFuncPtrObject instances */
3023 if (dict
->restype
) {
3024 Py_INCREF(dict
->restype
);
3025 return dict
->restype
;
3033 PyCFuncPtr_set_argtypes(PyCFuncPtrObject
*self
, PyObject
*ob
)
3035 PyObject
*converters
;
3037 if (ob
== NULL
|| ob
== Py_None
) {
3038 Py_XDECREF(self
->converters
);
3039 self
->converters
= NULL
;
3040 Py_XDECREF(self
->argtypes
);
3041 self
->argtypes
= NULL
;
3043 converters
= converters_from_argtypes(ob
);
3046 Py_XDECREF(self
->converters
);
3047 self
->converters
= converters
;
3048 Py_XDECREF(self
->argtypes
);
3050 self
->argtypes
= ob
;
3056 PyCFuncPtr_get_argtypes(PyCFuncPtrObject
*self
)
3058 StgDictObject
*dict
;
3059 if (self
->argtypes
) {
3060 Py_INCREF(self
->argtypes
);
3061 return self
->argtypes
;
3063 dict
= PyObject_stgdict((PyObject
*)self
);
3064 assert(dict
); /* Cannot be NULL for PyCFuncPtrObject instances */
3065 if (dict
->argtypes
) {
3066 Py_INCREF(dict
->argtypes
);
3067 return dict
->argtypes
;
3074 static PyGetSetDef PyCFuncPtr_getsets
[] = {
3075 { "errcheck", (getter
)PyCFuncPtr_get_errcheck
, (setter
)PyCFuncPtr_set_errcheck
,
3076 "a function to check for errors", NULL
},
3077 { "restype", (getter
)PyCFuncPtr_get_restype
, (setter
)PyCFuncPtr_set_restype
,
3078 "specify the result type", NULL
},
3079 { "argtypes", (getter
)PyCFuncPtr_get_argtypes
,
3080 (setter
)PyCFuncPtr_set_argtypes
,
3081 "specify the argument types", NULL
},
3086 static PPROC
FindAddress(void *handle
, char *name
, PyObject
*type
)
3089 /* win64 has no stdcall calling conv, so it should
3090 also not have the name mangling of it.
3092 return (PPROC
)GetProcAddress(handle
, name
);
3097 StgDictObject
*dict
;
3099 address
= (PPROC
)GetProcAddress(handle
, name
);
3102 if (((size_t)name
& ~0xFFFF) == 0) {
3106 dict
= PyType_stgdict((PyObject
*)type
);
3107 /* It should not happen that dict is NULL, but better be safe */
3108 if (dict
==NULL
|| dict
->flags
& FUNCFLAG_CDECL
)
3111 /* for stdcall, try mangled names:
3112 funcname -> _funcname@<n>
3113 where n is 0, 4, 8, 12, ..., 128
3115 mangled_name
= alloca(strlen(name
) + 1 + 1 + 1 + 3); /* \0 _ @ %d */
3118 for (i
= 0; i
< 32; ++i
) {
3119 sprintf(mangled_name
, "_%s@%d", name
, i
*4);
3120 address
= (PPROC
)GetProcAddress(handle
, mangled_name
);
3129 /* Return 1 if usable, 0 else and exception set. */
3131 _check_outarg_type(PyObject
*arg
, Py_ssize_t index
)
3133 StgDictObject
*dict
;
3135 if (PyCPointerTypeObject_Check(arg
))
3138 if (PyCArrayTypeObject_Check(arg
))
3141 dict
= PyType_stgdict(arg
);
3143 /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
3144 && PyString_Check(dict
->proto
)
3145 /* We only allow c_void_p, c_char_p and c_wchar_p as a simple output parameter type */
3146 && (strchr("PzZ", PyString_AS_STRING(dict
->proto
)[0]))) {
3150 PyErr_Format(PyExc_TypeError
,
3151 "'out' parameter %d must be a pointer type, not %s",
3152 Py_SAFE_DOWNCAST(index
, Py_ssize_t
, int),
3154 ((PyTypeObject
*)arg
)->tp_name
:
3155 Py_TYPE(arg
)->tp_name
);
3159 /* Returns 1 on success, 0 on error */
3161 _validate_paramflags(PyTypeObject
*type
, PyObject
*paramflags
)
3164 StgDictObject
*dict
;
3167 dict
= PyType_stgdict((PyObject
*)type
);
3168 assert(dict
); /* Cannot be NULL. 'type' is a PyCFuncPtr type. */
3169 argtypes
= dict
->argtypes
;
3171 if (paramflags
== NULL
|| dict
->argtypes
== NULL
)
3174 if (!PyTuple_Check(paramflags
)) {
3175 PyErr_SetString(PyExc_TypeError
,
3176 "paramflags must be a tuple or None");
3180 len
= PyTuple_GET_SIZE(paramflags
);
3181 if (len
!= PyTuple_GET_SIZE(dict
->argtypes
)) {
3182 PyErr_SetString(PyExc_ValueError
,
3183 "paramflags must have the same length as argtypes");
3187 for (i
= 0; i
< len
; ++i
) {
3188 PyObject
*item
= PyTuple_GET_ITEM(paramflags
, i
);
3193 if (!PyArg_ParseTuple(item
, "i|zO", &flag
, &name
, &defval
)) {
3194 PyErr_SetString(PyExc_TypeError
,
3195 "paramflags must be a sequence of (int [,string [,value]]) tuples");
3198 typ
= PyTuple_GET_ITEM(argtypes
, i
);
3199 switch (flag
& (PARAMFLAG_FIN
| PARAMFLAG_FOUT
| PARAMFLAG_FLCID
)) {
3202 case PARAMFLAG_FIN
| PARAMFLAG_FLCID
:
3203 case PARAMFLAG_FIN
| PARAMFLAG_FOUT
:
3205 case PARAMFLAG_FOUT
:
3206 if (!_check_outarg_type(typ
, i
+1))
3210 PyErr_Format(PyExc_TypeError
,
3211 "paramflag value %d not supported",
3220 _get_name(PyObject
*obj
, char **pname
)
3223 if (PyInt_Check(obj
) || PyLong_Check(obj
)) {
3224 /* We have to use MAKEINTRESOURCEA for Windows CE.
3225 Works on Windows as well, of course.
3227 *pname
= MAKEINTRESOURCEA(PyInt_AsUnsignedLongMask(obj
) & 0xFFFF);
3231 if (PyString_Check(obj
) || PyUnicode_Check(obj
)) {
3232 *pname
= PyString_AsString(obj
);
3233 return *pname
? 1 : 0;
3235 PyErr_SetString(PyExc_TypeError
,
3236 "function name must be string or integer");
3242 PyCFuncPtr_FromDll(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3245 int (* address
)(void);
3248 PyCFuncPtrObject
*self
;
3250 PyObject
*paramflags
= NULL
;
3252 if (!PyArg_ParseTuple(args
, "(O&O)|O", _get_name
, &name
, &dll
, ¶mflags
))
3254 if (paramflags
== Py_None
)
3257 obj
= PyObject_GetAttrString(dll
, "_handle");
3260 if (!PyInt_Check(obj
) && !PyLong_Check(obj
)) {
3261 PyErr_SetString(PyExc_TypeError
,
3262 "the _handle attribute of the second argument must be an integer");
3266 handle
= (void *)PyLong_AsVoidPtr(obj
);
3268 if (PyErr_Occurred()) {
3269 PyErr_SetString(PyExc_ValueError
,
3270 "could not convert the _handle attribute to a pointer");
3275 address
= FindAddress(handle
, name
, (PyObject
*)type
);
3277 if (!IS_INTRESOURCE(name
))
3278 PyErr_Format(PyExc_AttributeError
,
3279 "function '%s' not found",
3282 PyErr_Format(PyExc_AttributeError
,
3283 "function ordinal %d not found",
3284 (WORD
)(size_t)name
);
3288 address
= (PPROC
)ctypes_dlsym(handle
, name
);
3291 /* dlerror() isn't very helpful on cygwin */
3292 PyErr_Format(PyExc_AttributeError
,
3293 "function '%s' not found (%s) ",
3296 PyErr_SetString(PyExc_AttributeError
, ctypes_dlerror());
3301 if (!_validate_paramflags(type
, paramflags
))
3304 self
= (PyCFuncPtrObject
*)GenericPyCData_new(type
, args
, kwds
);
3308 Py_XINCREF(paramflags
);
3309 self
->paramflags
= paramflags
;
3311 *(void **)self
->b_ptr
= address
;
3313 Py_INCREF((PyObject
*)dll
); /* for KeepRef */
3314 if (-1 == KeepRef((CDataObject
*)self
, 0, dll
)) {
3315 Py_DECREF((PyObject
*)self
);
3320 self
->callable
= (PyObject
*)self
;
3321 return (PyObject
*)self
;
3326 PyCFuncPtr_FromVtblIndex(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3328 PyCFuncPtrObject
*self
;
3331 PyObject
*paramflags
= NULL
;
3333 Py_ssize_t iid_len
= 0;
3335 if (!PyArg_ParseTuple(args
, "is|Oz#", &index
, &name
, ¶mflags
, &iid
, &iid_len
))
3337 if (paramflags
== Py_None
)
3340 if (!_validate_paramflags(type
, paramflags
))
3343 self
= (PyCFuncPtrObject
*)GenericPyCData_new(type
, args
, kwds
);
3344 self
->index
= index
+ 0x1000;
3345 Py_XINCREF(paramflags
);
3346 self
->paramflags
= paramflags
;
3347 if (iid_len
== sizeof(GUID
))
3349 return (PyObject
*)self
;
3354 PyCFuncPtr_new accepts different argument lists in addition to the standard
3355 _basespec_ keyword arg:
3358 "i" - function address
3359 "O" - must be a callable, creates a C callable function
3361 two or more argument forms (the third argument is a paramflags tuple)
3362 "(sO)|..." - (function name, dll object (with an integer handle)), paramflags
3363 "(iO)|..." - (function ordinal, dll object (with an integer handle)), paramflags
3364 "is|..." - vtable index, method name, creates callable calling COM vtbl
3367 PyCFuncPtr_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3369 PyCFuncPtrObject
*self
;
3371 StgDictObject
*dict
;
3372 CThunkObject
*thunk
;
3374 if (PyTuple_GET_SIZE(args
) == 0)
3375 return GenericPyCData_new(type
, args
, kwds
);
3377 if (1 <= PyTuple_GET_SIZE(args
) && PyTuple_Check(PyTuple_GET_ITEM(args
, 0)))
3378 return PyCFuncPtr_FromDll(type
, args
, kwds
);
3381 if (2 <= PyTuple_GET_SIZE(args
) && PyInt_Check(PyTuple_GET_ITEM(args
, 0)))
3382 return PyCFuncPtr_FromVtblIndex(type
, args
, kwds
);
3385 if (1 == PyTuple_GET_SIZE(args
)
3386 && (PyInt_Check(PyTuple_GET_ITEM(args
, 0))
3387 || PyLong_Check(PyTuple_GET_ITEM(args
, 0)))) {
3389 void *ptr
= PyLong_AsVoidPtr(PyTuple_GET_ITEM(args
, 0));
3390 if (ptr
== NULL
&& PyErr_Occurred())
3392 ob
= (CDataObject
*)GenericPyCData_new(type
, args
, kwds
);
3395 *(void **)ob
->b_ptr
= ptr
;
3396 return (PyObject
*)ob
;
3399 if (!PyArg_ParseTuple(args
, "O", &callable
))
3401 if (!PyCallable_Check(callable
)) {
3402 PyErr_SetString(PyExc_TypeError
,
3403 "argument must be callable or integer function address");
3407 /* XXX XXX This would allow to pass additional options. For COM
3408 method *implementations*, we would probably want different
3409 behaviour than in 'normal' callback functions: return a HRESULT if
3410 an exception occurrs in the callback, and print the traceback not
3411 only on the console, but also to OutputDebugString() or something
3415 if (kwds && PyDict_GetItemString(kwds, "options")) {
3420 dict
= PyType_stgdict((PyObject
*)type
);
3421 /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */
3422 if (!dict
|| !dict
->argtypes
) {
3423 PyErr_SetString(PyExc_TypeError
,
3424 "cannot construct instance of this class:"
3429 thunk
= _ctypes_alloc_callback(callable
,
3436 self
= (PyCFuncPtrObject
*)GenericPyCData_new(type
, args
, kwds
);
3442 Py_INCREF(callable
);
3443 self
->callable
= callable
;
3445 self
->thunk
= thunk
;
3446 *(void **)self
->b_ptr
= (void *)thunk
->pcl
;
3448 Py_INCREF((PyObject
*)thunk
); /* for KeepRef */
3449 if (-1 == KeepRef((CDataObject
*)self
, 0, (PyObject
*)thunk
)) {
3450 Py_DECREF((PyObject
*)self
);
3453 return (PyObject
*)self
;
3458 _byref consumes a refcount to its argument
3461 _byref(PyObject
*obj
)
3464 if (!CDataObject_Check(obj
)) {
3465 PyErr_SetString(PyExc_TypeError
,
3466 "expected CData instance");
3470 parg
= PyCArgObject_new();
3477 parg
->pffi_type
= &ffi_type_pointer
;
3479 parg
->value
.p
= ((CDataObject
*)obj
)->b_ptr
;
3480 return (PyObject
*)parg
;
3484 _get_arg(int *pindex
, char *name
, PyObject
*defval
, PyObject
*inargs
, PyObject
*kwds
)
3488 if (*pindex
< PyTuple_GET_SIZE(inargs
)) {
3489 v
= PyTuple_GET_ITEM(inargs
, *pindex
);
3494 if (kwds
&& (v
= PyDict_GetItemString(kwds
, name
))) {
3503 /* we can't currently emit a better error message */
3505 PyErr_Format(PyExc_TypeError
,
3506 "required argument '%s' missing", name
);
3508 PyErr_Format(PyExc_TypeError
,
3509 "not enough arguments");
3514 This function implements higher level functionality plus the ability to call
3515 functions with keyword arguments by looking at parameter flags. parameter
3516 flags is a tuple of 1, 2 or 3-tuples. The first entry in each is an integer
3517 specifying the direction of the data transfer for this parameter - 'in',
3518 'out' or 'inout' (zero means the same as 'in'). The second entry is the
3519 parameter name, and the third is the default value if the parameter is
3520 missing in the function call.
3522 This function builds and returns a new tuple 'callargs' which contains the
3523 parameters to use in the call. Items on this tuple are copied from the
3524 'inargs' tuple for 'in' and 'in, out' parameters, and constructed from the
3525 'argtypes' tuple for 'out' parameters. It also calculates numretvals which
3526 is the number of return values for the function, outmask/inoutmask are
3527 bitmasks containing indexes into the callargs tuple specifying which
3528 parameters have to be returned. _build_result builds the return value of the
3532 _build_callargs(PyCFuncPtrObject
*self
, PyObject
*argtypes
,
3533 PyObject
*inargs
, PyObject
*kwds
,
3534 int *poutmask
, int *pinoutmask
, unsigned int *pnumretvals
)
3536 PyObject
*paramflags
= self
->paramflags
;
3538 StgDictObject
*dict
;
3540 int inargs_index
= 0;
3541 /* It's a little bit difficult to determine how many arguments the
3542 function call requires/accepts. For simplicity, we count the consumed
3543 args and compare this to the number of supplied args. */
3544 Py_ssize_t actual_args
;
3550 /* Trivial cases, where we either return inargs itself, or a slice of it. */
3551 if (argtypes
== NULL
|| paramflags
== NULL
|| PyTuple_GET_SIZE(argtypes
) == 0) {
3554 return PyTuple_GetSlice(inargs
, 1, PyTuple_GET_SIZE(inargs
));
3560 len
= PyTuple_GET_SIZE(argtypes
);
3561 callargs
= PyTuple_New(len
); /* the argument tuple we build */
3562 if (callargs
== NULL
)
3566 /* For a COM method, skip the first arg */
3571 for (i
= 0; i
< len
; ++i
) {
3572 PyObject
*item
= PyTuple_GET_ITEM(paramflags
, i
);
3576 PyObject
*defval
= NULL
;
3578 /* This way seems to be ~2 us faster than the PyArg_ParseTuple
3580 /* We HAVE already checked that the tuple can be parsed with "i|zO", so... */
3581 Py_ssize_t tsize
= PyTuple_GET_SIZE(item
);
3582 flag
= PyInt_AS_LONG(PyTuple_GET_ITEM(item
, 0));
3583 name
= tsize
> 1 ? PyString_AS_STRING(PyTuple_GET_ITEM(item
, 1)) : NULL
;
3584 defval
= tsize
> 2 ? PyTuple_GET_ITEM(item
, 2) : NULL
;
3586 switch (flag
& (PARAMFLAG_FIN
| PARAMFLAG_FOUT
| PARAMFLAG_FLCID
)) {
3587 case PARAMFLAG_FIN
| PARAMFLAG_FLCID
:
3588 /* ['in', 'lcid'] parameter. Always taken from defval,
3589 if given, else the integer 0. */
3590 if (defval
== NULL
) {
3591 defval
= PyInt_FromLong(0);
3596 PyTuple_SET_ITEM(callargs
, i
, defval
);
3598 case (PARAMFLAG_FIN
| PARAMFLAG_FOUT
):
3599 *pinoutmask
|= (1 << i
); /* mark as inout arg */
3601 /* fall through to PARAMFLAG_FIN... */
3604 /* 'in' parameter. Copy it from inargs. */
3605 ob
=_get_arg(&inargs_index
, name
, defval
, inargs
, kwds
);
3608 PyTuple_SET_ITEM(callargs
, i
, ob
);
3610 case PARAMFLAG_FOUT
:
3611 /* XXX Refactor this code into a separate function. */
3613 argtypes[i] must be a POINTER to a c type.
3615 Cannot by supplied in inargs, but a defval will be used
3616 if available. XXX Should we support getting it from kwds?
3619 /* XXX Using mutable objects as defval will
3620 make the function non-threadsafe, unless we
3621 copy the object in each invocation */
3623 PyTuple_SET_ITEM(callargs
, i
, defval
);
3624 *poutmask
|= (1 << i
); /* mark as out arg */
3628 ob
= PyTuple_GET_ITEM(argtypes
, i
);
3629 dict
= PyType_stgdict(ob
);
3631 /* Cannot happen: _validate_paramflags()
3632 would not accept such an object */
3633 PyErr_Format(PyExc_RuntimeError
,
3634 "NULL stgdict unexpected");
3637 if (PyString_Check(dict
->proto
)) {
3640 "%s 'out' parameter must be passed as default value",
3641 ((PyTypeObject
*)ob
)->tp_name
);
3644 if (PyCArrayTypeObject_Check(ob
))
3645 ob
= PyObject_CallObject(ob
, NULL
);
3647 /* Create an instance of the pointed-to type */
3648 ob
= PyObject_CallObject(dict
->proto
, NULL
);
3650 XXX Is the following correct any longer?
3651 We must not pass a byref() to the array then but
3652 the array instance itself. Then, we cannot retrive
3653 the result from the PyCArgObject.
3657 /* The .from_param call that will ocurr later will pass this
3658 as a byref parameter. */
3659 PyTuple_SET_ITEM(callargs
, i
, ob
);
3660 *poutmask
|= (1 << i
); /* mark as out arg */
3664 PyErr_Format(PyExc_ValueError
,
3665 "paramflag %d not yet implemented", flag
);
3671 /* We have counted the arguments we have consumed in 'inargs_index'. This
3672 must be the same as len(inargs) + len(kwds), otherwise we have
3673 either too much or not enough arguments. */
3675 actual_args
= PyTuple_GET_SIZE(inargs
) + (kwds
? PyDict_Size(kwds
) : 0);
3676 if (actual_args
!= inargs_index
) {
3677 /* When we have default values or named parameters, this error
3678 message is misleading. See unittests/test_paramflags.py
3680 PyErr_Format(PyExc_TypeError
,
3681 #if (PY_VERSION_HEX < 0x02050000)
3682 "call takes exactly %d arguments (%d given)",
3684 "call takes exactly %d arguments (%zd given)",
3686 inargs_index
, actual_args
);
3690 /* outmask is a bitmask containing indexes into callargs. Items at
3691 these indexes contain values to return.
3695 Py_DECREF(callargs
);
3700 http://msdn.microsoft.com/library/en-us/com/html/769127a1-1a14-4ed4-9d38-7cf3e571b661.asp
3703 Build return value of a function.
3705 Consumes the refcount on result and callargs.
3708 _build_result(PyObject
*result
, PyObject
*callargs
,
3709 int outmask
, int inoutmask
, unsigned int numretvals
)
3711 unsigned int i
, index
;
3713 PyObject
*tup
= NULL
;
3715 if (callargs
== NULL
)
3717 if (result
== NULL
|| numretvals
== 0) {
3718 Py_DECREF(callargs
);
3723 /* tup will not be allocated if numretvals == 1 */
3724 /* allocate tuple to hold the result */
3725 if (numretvals
> 1) {
3726 tup
= PyTuple_New(numretvals
);
3728 Py_DECREF(callargs
);
3734 for (bit
= 1, i
= 0; i
< 32; ++i
, bit
<<= 1) {
3736 if (bit
& inoutmask
) {
3737 v
= PyTuple_GET_ITEM(callargs
, i
);
3739 if (numretvals
== 1) {
3740 Py_DECREF(callargs
);
3743 PyTuple_SET_ITEM(tup
, index
, v
);
3745 } else if (bit
& outmask
) {
3746 v
= PyTuple_GET_ITEM(callargs
, i
);
3747 v
= PyObject_CallMethod(v
, "__ctypes_from_outparam__", NULL
);
3748 if (v
== NULL
|| numretvals
== 1) {
3749 Py_DECREF(callargs
);
3752 PyTuple_SET_ITEM(tup
, index
, v
);
3755 if (index
== numretvals
)
3759 Py_DECREF(callargs
);
3764 PyCFuncPtr_call(PyCFuncPtrObject
*self
, PyObject
*inargs
, PyObject
*kwds
)
3767 PyObject
*converters
;
3770 StgDictObject
*dict
= PyObject_stgdict((PyObject
*)self
);
3775 IUnknown
*piunk
= NULL
;
3781 unsigned int numretvals
;
3783 assert(dict
); /* Cannot be NULL for PyCFuncPtrObject instances */
3784 restype
= self
->restype
? self
->restype
: dict
->restype
;
3785 converters
= self
->converters
? self
->converters
: dict
->converters
;
3786 checker
= self
->checker
? self
->checker
: dict
->checker
;
3787 argtypes
= self
->argtypes
? self
->argtypes
: dict
->argtypes
;
3788 /* later, we probably want to have an errcheck field in stgdict */
3789 errcheck
= self
->errcheck
/* ? self->errcheck : dict->errcheck */;
3792 pProc
= *(void **)self
->b_ptr
;
3795 /* It's a COM method */
3797 this = (CDataObject
*)PyTuple_GetItem(inargs
, 0); /* borrowed ref! */
3799 PyErr_SetString(PyExc_ValueError
,
3800 "native com method call without 'this' parameter");
3803 if (!CDataObject_Check(this)) {
3804 PyErr_SetString(PyExc_TypeError
,
3805 "Expected a COM this pointer as first argument");
3808 /* there should be more checks? No, in Python */
3809 /* First arg is an pointer to an interface instance */
3810 if (!this->b_ptr
|| *(void **)this->b_ptr
== NULL
) {
3811 PyErr_SetString(PyExc_ValueError
,
3812 "NULL COM pointer access");
3815 piunk
= *(IUnknown
**)this->b_ptr
;
3816 if (NULL
== piunk
->lpVtbl
) {
3817 PyErr_SetString(PyExc_ValueError
,
3818 "COM method call without VTable");
3821 pProc
= ((void **)piunk
->lpVtbl
)[self
->index
- 0x1000];
3824 callargs
= _build_callargs(self
, argtypes
,
3826 &outmask
, &inoutmask
, &numretvals
);
3827 if (callargs
== NULL
)
3831 int required
= Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters
),
3833 int actual
= Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs
),
3836 if ((dict
->flags
& FUNCFLAG_CDECL
) == FUNCFLAG_CDECL
) {
3837 /* For cdecl functions, we allow more actual arguments
3838 than the length of the argtypes tuple.
3840 if (required
> actual
) {
3841 Py_DECREF(callargs
);
3842 PyErr_Format(PyExc_TypeError
,
3843 "this function takes at least %d argument%s (%d given)",
3845 required
== 1 ? "" : "s",
3849 } else if (required
!= actual
) {
3850 Py_DECREF(callargs
);
3851 PyErr_Format(PyExc_TypeError
,
3852 "this function takes %d argument%s (%d given)",
3854 required
== 1 ? "" : "s",
3860 result
= _ctypes_callproc(pProc
,
3870 /* The 'errcheck' protocol */
3871 if (result
!= NULL
&& errcheck
) {
3872 PyObject
*v
= PyObject_CallFunctionObjArgs(errcheck
,
3877 /* If the errcheck funtion failed, return NULL.
3878 If the errcheck function returned callargs unchanged,
3879 continue normal processing.
3880 If the errcheck function returned something else,
3883 if (v
== NULL
|| v
!= callargs
) {
3885 Py_DECREF(callargs
);
3891 return _build_result(result
, callargs
,
3892 outmask
, inoutmask
, numretvals
);
3896 PyCFuncPtr_traverse(PyCFuncPtrObject
*self
, visitproc visit
, void *arg
)
3898 Py_VISIT(self
->callable
);
3899 Py_VISIT(self
->restype
);
3900 Py_VISIT(self
->checker
);
3901 Py_VISIT(self
->errcheck
);
3902 Py_VISIT(self
->argtypes
);
3903 Py_VISIT(self
->converters
);
3904 Py_VISIT(self
->paramflags
);
3905 Py_VISIT(self
->thunk
);
3906 return PyCData_traverse((CDataObject
*)self
, visit
, arg
);
3910 PyCFuncPtr_clear(PyCFuncPtrObject
*self
)
3912 Py_CLEAR(self
->callable
);
3913 Py_CLEAR(self
->restype
);
3914 Py_CLEAR(self
->checker
);
3915 Py_CLEAR(self
->errcheck
);
3916 Py_CLEAR(self
->argtypes
);
3917 Py_CLEAR(self
->converters
);
3918 Py_CLEAR(self
->paramflags
);
3919 Py_CLEAR(self
->thunk
);
3920 return PyCData_clear((CDataObject
*)self
);
3924 PyCFuncPtr_dealloc(PyCFuncPtrObject
*self
)
3926 PyCFuncPtr_clear(self
);
3927 Py_TYPE(self
)->tp_free((PyObject
*)self
);
3931 PyCFuncPtr_repr(PyCFuncPtrObject
*self
)
3935 return PyString_FromFormat("<COM method offset %d: %s at %p>",
3936 self
->index
- 0x1000,
3937 Py_TYPE(self
)->tp_name
,
3940 return PyString_FromFormat("<%s object at %p>",
3941 Py_TYPE(self
)->tp_name
,
3946 PyCFuncPtr_nonzero(PyCFuncPtrObject
*self
)
3948 return ((*(void **)self
->b_ptr
!= NULL
)
3950 || (self
->index
!= 0)
3955 static PyNumberMethods PyCFuncPtr_as_number
= {
3957 0, /* nb_subtract */
3958 0, /* nb_multiply */
3960 0, /* nb_remainder */
3963 0, /* nb_negative */
3964 0, /* nb_positive */
3965 0, /* nb_absolute */
3966 (inquiry
)PyCFuncPtr_nonzero
, /* nb_nonzero */
3969 PyTypeObject PyCFuncPtr_Type
= {
3970 PyVarObject_HEAD_INIT(NULL
, 0)
3971 "_ctypes.PyCFuncPtr",
3972 sizeof(PyCFuncPtrObject
), /* tp_basicsize */
3973 0, /* tp_itemsize */
3974 (destructor
)PyCFuncPtr_dealloc
, /* tp_dealloc */
3979 (reprfunc
)PyCFuncPtr_repr
, /* tp_repr */
3980 &PyCFuncPtr_as_number
, /* tp_as_number */
3981 0, /* tp_as_sequence */
3982 0, /* tp_as_mapping */
3984 (ternaryfunc
)PyCFuncPtr_call
, /* tp_call */
3986 0, /* tp_getattro */
3987 0, /* tp_setattro */
3988 &PyCData_as_buffer
, /* tp_as_buffer */
3989 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_NEWBUFFER
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
3990 "Function Pointer", /* tp_doc */
3991 (traverseproc
)PyCFuncPtr_traverse
, /* tp_traverse */
3992 (inquiry
)PyCFuncPtr_clear
, /* tp_clear */
3993 0, /* tp_richcompare */
3994 0, /* tp_weaklistoffset */
3996 0, /* tp_iternext */
3999 PyCFuncPtr_getsets
, /* tp_getset */
4002 0, /* tp_descr_get */
4003 0, /* tp_descr_set */
4004 0, /* tp_dictoffset */
4007 PyCFuncPtr_new
, /* tp_new */
4011 /*****************************************************************/
4016 This function is called to initialize a Structure or Union with positional
4017 arguments. It calls itself recursively for all Structure or Union base
4018 classes, then retrieves the _fields_ member to associate the argument
4019 position with the correct field name.
4021 Returns -1 on error, or the index of next argument on success.
4024 _init_pos_args(PyObject
*self
, PyTypeObject
*type
,
4025 PyObject
*args
, PyObject
*kwds
,
4028 StgDictObject
*dict
;
4032 if (PyType_stgdict((PyObject
*)type
->tp_base
)) {
4033 index
= _init_pos_args(self
, type
->tp_base
,
4040 dict
= PyType_stgdict((PyObject
*)type
);
4041 fields
= PyDict_GetItemString((PyObject
*)dict
, "_fields_");
4046 i
< dict
->length
&& (i
+index
) < PyTuple_GET_SIZE(args
);
4048 PyObject
*pair
= PySequence_GetItem(fields
, i
);
4049 PyObject
*name
, *val
;
4053 name
= PySequence_GetItem(pair
, 0);
4058 val
= PyTuple_GET_ITEM(args
, i
+ index
);
4059 if (kwds
&& PyDict_GetItem(kwds
, name
)) {
4060 char *field
= PyString_AsString(name
);
4061 if (field
== NULL
) {
4065 PyErr_Format(PyExc_TypeError
,
4066 "duplicate values for field '%s'",
4073 res
= PyObject_SetAttr(self
, name
, val
);
4079 return index
+ dict
->length
;
4083 Struct_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
4085 /* Optimization possible: Store the attribute names _fields_[x][0]
4086 * in C accessible fields somewhere ?
4088 if (!PyTuple_Check(args
)) {
4089 PyErr_SetString(PyExc_TypeError
,
4090 "args not a tuple?");
4093 if (PyTuple_GET_SIZE(args
)) {
4094 int res
= _init_pos_args(self
, Py_TYPE(self
),
4098 if (res
< PyTuple_GET_SIZE(args
)) {
4099 PyErr_SetString(PyExc_TypeError
,
4100 "too many initializers");
4106 PyObject
*key
, *value
;
4108 while(PyDict_Next(kwds
, &pos
, &key
, &value
)) {
4109 if (-1 == PyObject_SetAttr(self
, key
, value
))
4116 static PyTypeObject Struct_Type
= {
4117 PyVarObject_HEAD_INIT(NULL
, 0)
4118 "_ctypes.Structure",
4119 sizeof(CDataObject
), /* tp_basicsize */
4120 0, /* tp_itemsize */
4127 0, /* tp_as_number */
4128 0, /* tp_as_sequence */
4129 0, /* tp_as_mapping */
4133 0, /* tp_getattro */
4134 0, /* tp_setattro */
4135 &PyCData_as_buffer
, /* tp_as_buffer */
4136 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_NEWBUFFER
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
4137 "Structure base class", /* tp_doc */
4138 (traverseproc
)PyCData_traverse
, /* tp_traverse */
4139 (inquiry
)PyCData_clear
, /* tp_clear */
4140 0, /* tp_richcompare */
4141 0, /* tp_weaklistoffset */
4143 0, /* tp_iternext */
4149 0, /* tp_descr_get */
4150 0, /* tp_descr_set */
4151 0, /* tp_dictoffset */
4152 Struct_init
, /* tp_init */
4154 GenericPyCData_new
, /* tp_new */
4158 static PyTypeObject Union_Type
= {
4159 PyVarObject_HEAD_INIT(NULL
, 0)
4161 sizeof(CDataObject
), /* tp_basicsize */
4162 0, /* tp_itemsize */
4169 0, /* tp_as_number */
4170 0, /* tp_as_sequence */
4171 0, /* tp_as_mapping */
4175 0, /* tp_getattro */
4176 0, /* tp_setattro */
4177 &PyCData_as_buffer
, /* tp_as_buffer */
4178 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_NEWBUFFER
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
4179 "Union base class", /* tp_doc */
4180 (traverseproc
)PyCData_traverse
, /* tp_traverse */
4181 (inquiry
)PyCData_clear
, /* tp_clear */
4182 0, /* tp_richcompare */
4183 0, /* tp_weaklistoffset */
4185 0, /* tp_iternext */
4191 0, /* tp_descr_get */
4192 0, /* tp_descr_set */
4193 0, /* tp_dictoffset */
4194 Struct_init
, /* tp_init */
4196 GenericPyCData_new
, /* tp_new */
4201 /******************************************************************/
4206 Array_init(CDataObject
*self
, PyObject
*args
, PyObject
*kw
)
4211 if (!PyTuple_Check(args
)) {
4212 PyErr_SetString(PyExc_TypeError
,
4213 "args not a tuple?");
4216 n
= PyTuple_GET_SIZE(args
);
4217 for (i
= 0; i
< n
; ++i
) {
4219 v
= PyTuple_GET_ITEM(args
, i
);
4220 if (-1 == PySequence_SetItem((PyObject
*)self
, i
, v
))
4227 Array_item(PyObject
*_self
, Py_ssize_t index
)
4229 CDataObject
*self
= (CDataObject
*)_self
;
4230 Py_ssize_t offset
, size
;
4231 StgDictObject
*stgdict
;
4234 if (index
< 0 || index
>= self
->b_length
) {
4235 PyErr_SetString(PyExc_IndexError
,
4240 stgdict
= PyObject_stgdict((PyObject
*)self
);
4241 assert(stgdict
); /* Cannot be NULL for array instances */
4242 /* Would it be clearer if we got the item size from
4243 stgdict->proto's stgdict?
4245 size
= stgdict
->size
/ stgdict
->length
;
4246 offset
= index
* size
;
4248 return PyCData_get(stgdict
->proto
, stgdict
->getfunc
, (PyObject
*)self
,
4249 index
, size
, self
->b_ptr
+ offset
);
4253 Array_slice(PyObject
*_self
, Py_ssize_t ilow
, Py_ssize_t ihigh
)
4255 CDataObject
*self
= (CDataObject
*)_self
;
4256 StgDictObject
*stgdict
, *itemdict
;
4263 else if (ilow
> self
->b_length
)
4264 ilow
= self
->b_length
;
4267 else if (ihigh
> self
->b_length
)
4268 ihigh
= self
->b_length
;
4271 stgdict
= PyObject_stgdict((PyObject
*)self
);
4272 assert(stgdict
); /* Cannot be NULL for array object instances */
4273 proto
= stgdict
->proto
;
4274 itemdict
= PyType_stgdict(proto
);
4275 assert(itemdict
); /* proto is the item type of the array, a ctypes
4276 type, so this cannot be NULL */
4277 if (itemdict
->getfunc
== _ctypes_get_fielddesc("c")->getfunc
) {
4278 char *ptr
= (char *)self
->b_ptr
;
4279 return PyString_FromStringAndSize(ptr
+ ilow
, len
);
4280 #ifdef CTYPES_UNICODE
4281 } else if (itemdict
->getfunc
== _ctypes_get_fielddesc("u")->getfunc
) {
4282 wchar_t *ptr
= (wchar_t *)self
->b_ptr
;
4283 return PyUnicode_FromWideChar(ptr
+ ilow
, len
);
4287 np
= (PyListObject
*) PyList_New(len
);
4291 for (i
= 0; i
< len
; i
++) {
4292 PyObject
*v
= Array_item(_self
, i
+ilow
);
4293 PyList_SET_ITEM(np
, i
, v
);
4295 return (PyObject
*)np
;
4299 Array_subscript(PyObject
*_self
, PyObject
*item
)
4301 CDataObject
*self
= (CDataObject
*)_self
;
4303 if (PyIndex_Check(item
)) {
4304 Py_ssize_t i
= PyNumber_AsSsize_t(item
, PyExc_IndexError
);
4306 if (i
== -1 && PyErr_Occurred())
4309 i
+= self
->b_length
;
4310 return Array_item(_self
, i
);
4312 else if PySlice_Check(item
) {
4313 StgDictObject
*stgdict
, *itemdict
;
4316 Py_ssize_t start
, stop
, step
, slicelen
, cur
, i
;
4318 if (PySlice_GetIndicesEx((PySliceObject
*)item
,
4319 self
->b_length
, &start
, &stop
,
4320 &step
, &slicelen
) < 0) {
4324 stgdict
= PyObject_stgdict((PyObject
*)self
);
4325 assert(stgdict
); /* Cannot be NULL for array object instances */
4326 proto
= stgdict
->proto
;
4327 itemdict
= PyType_stgdict(proto
);
4328 assert(itemdict
); /* proto is the item type of the array, a
4329 ctypes type, so this cannot be NULL */
4331 if (itemdict
->getfunc
== _ctypes_get_fielddesc("c")->getfunc
) {
4332 char *ptr
= (char *)self
->b_ptr
;
4336 return PyString_FromString("");
4338 return PyString_FromStringAndSize(ptr
+ start
,
4341 dest
= (char *)PyMem_Malloc(slicelen
);
4344 return PyErr_NoMemory();
4346 for (cur
= start
, i
= 0; i
< slicelen
;
4351 np
= PyString_FromStringAndSize(dest
, slicelen
);
4355 #ifdef CTYPES_UNICODE
4356 if (itemdict
->getfunc
== _ctypes_get_fielddesc("u")->getfunc
) {
4357 wchar_t *ptr
= (wchar_t *)self
->b_ptr
;
4361 return PyUnicode_FromUnicode(NULL
, 0);
4363 return PyUnicode_FromWideChar(ptr
+ start
,
4367 dest
= (wchar_t *)PyMem_Malloc(
4368 slicelen
* sizeof(wchar_t));
4370 for (cur
= start
, i
= 0; i
< slicelen
;
4375 np
= PyUnicode_FromWideChar(dest
, slicelen
);
4381 np
= PyList_New(slicelen
);
4385 for (cur
= start
, i
= 0; i
< slicelen
;
4387 PyObject
*v
= Array_item(_self
, cur
);
4388 PyList_SET_ITEM(np
, i
, v
);
4393 PyErr_SetString(PyExc_TypeError
,
4394 "indices must be integers");
4401 Array_ass_item(PyObject
*_self
, Py_ssize_t index
, PyObject
*value
)
4403 CDataObject
*self
= (CDataObject
*)_self
;
4404 Py_ssize_t size
, offset
;
4405 StgDictObject
*stgdict
;
4408 if (value
== NULL
) {
4409 PyErr_SetString(PyExc_TypeError
,
4410 "Array does not support item deletion");
4414 stgdict
= PyObject_stgdict((PyObject
*)self
);
4415 assert(stgdict
); /* Cannot be NULL for array object instances */
4416 if (index
< 0 || index
>= stgdict
->length
) {
4417 PyErr_SetString(PyExc_IndexError
,
4421 size
= stgdict
->size
/ stgdict
->length
;
4422 offset
= index
* size
;
4423 ptr
= self
->b_ptr
+ offset
;
4425 return PyCData_set((PyObject
*)self
, stgdict
->proto
, stgdict
->setfunc
, value
,
4430 Array_ass_slice(PyObject
*_self
, Py_ssize_t ilow
, Py_ssize_t ihigh
, PyObject
*value
)
4432 CDataObject
*self
= (CDataObject
*)_self
;
4435 if (value
== NULL
) {
4436 PyErr_SetString(PyExc_TypeError
,
4437 "Array does not support item deletion");
4443 else if (ilow
> self
->b_length
)
4444 ilow
= self
->b_length
;
4449 else if (ihigh
> self
->b_length
)
4450 ihigh
= self
->b_length
;
4452 len
= PySequence_Length(value
);
4453 if (len
!= ihigh
- ilow
) {
4454 PyErr_SetString(PyExc_ValueError
,
4455 "Can only assign sequence of same size");
4458 for (i
= 0; i
< len
; i
++) {
4459 PyObject
*item
= PySequence_GetItem(value
, i
);
4463 result
= Array_ass_item(_self
, i
+ilow
, item
);
4472 Array_ass_subscript(PyObject
*_self
, PyObject
*item
, PyObject
*value
)
4474 CDataObject
*self
= (CDataObject
*)_self
;
4476 if (value
== NULL
) {
4477 PyErr_SetString(PyExc_TypeError
,
4478 "Array does not support item deletion");
4482 if (PyIndex_Check(item
)) {
4483 Py_ssize_t i
= PyNumber_AsSsize_t(item
, PyExc_IndexError
);
4485 if (i
== -1 && PyErr_Occurred())
4488 i
+= self
->b_length
;
4489 return Array_ass_item(_self
, i
, value
);
4491 else if (PySlice_Check(item
)) {
4492 Py_ssize_t start
, stop
, step
, slicelen
, otherlen
, i
, cur
;
4494 if (PySlice_GetIndicesEx((PySliceObject
*)item
,
4495 self
->b_length
, &start
, &stop
,
4496 &step
, &slicelen
) < 0) {
4499 if ((step
< 0 && start
< stop
) ||
4500 (step
> 0 && start
> stop
))
4503 otherlen
= PySequence_Length(value
);
4504 if (otherlen
!= slicelen
) {
4505 PyErr_SetString(PyExc_ValueError
,
4506 "Can only assign sequence of same size");
4509 for (cur
= start
, i
= 0; i
< otherlen
; cur
+= step
, i
++) {
4510 PyObject
*item
= PySequence_GetItem(value
, i
);
4514 result
= Array_ass_item(_self
, cur
, item
);
4522 PyErr_SetString(PyExc_TypeError
,
4523 "indices must be integer");
4529 Array_length(PyObject
*_self
)
4531 CDataObject
*self
= (CDataObject
*)_self
;
4532 return self
->b_length
;
4535 static PySequenceMethods Array_as_sequence
= {
4536 Array_length
, /* sq_length; */
4539 Array_item
, /* sq_item; */
4540 Array_slice
, /* sq_slice; */
4541 Array_ass_item
, /* sq_ass_item; */
4542 Array_ass_slice
, /* sq_ass_slice; */
4543 0, /* sq_contains; */
4545 0, /* sq_inplace_concat; */
4546 0, /* sq_inplace_repeat; */
4549 static PyMappingMethods Array_as_mapping
= {
4552 Array_ass_subscript
,
4555 PyTypeObject PyCArray_Type
= {
4556 PyVarObject_HEAD_INIT(NULL
, 0)
4558 sizeof(CDataObject
), /* tp_basicsize */
4559 0, /* tp_itemsize */
4566 0, /* tp_as_number */
4567 &Array_as_sequence
, /* tp_as_sequence */
4568 &Array_as_mapping
, /* tp_as_mapping */
4572 0, /* tp_getattro */
4573 0, /* tp_setattro */
4574 &PyCData_as_buffer
, /* tp_as_buffer */
4575 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_NEWBUFFER
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
4576 "XXX to be provided", /* tp_doc */
4577 (traverseproc
)PyCData_traverse
, /* tp_traverse */
4578 (inquiry
)PyCData_clear
, /* tp_clear */
4579 0, /* tp_richcompare */
4580 0, /* tp_weaklistoffset */
4582 0, /* tp_iternext */
4588 0, /* tp_descr_get */
4589 0, /* tp_descr_set */
4590 0, /* tp_dictoffset */
4591 (initproc
)Array_init
, /* tp_init */
4593 GenericPyCData_new
, /* tp_new */
4598 PyCArrayType_from_ctype(PyObject
*itemtype
, Py_ssize_t length
)
4600 static PyObject
*cache
;
4606 if (cache
== NULL
) {
4607 cache
= PyDict_New();
4611 len
= PyInt_FromSsize_t(length
);
4614 key
= PyTuple_Pack(2, itemtype
, len
);
4618 result
= PyDict_GetItemProxy(cache
, key
);
4625 if (!PyType_Check(itemtype
)) {
4626 PyErr_SetString(PyExc_TypeError
,
4627 "Expected a type object");
4631 sprintf(name
, "%.200s_Array_%Id",
4632 ((PyTypeObject
*)itemtype
)->tp_name
, length
);
4634 sprintf(name
, "%.200s_Array_%ld",
4635 ((PyTypeObject
*)itemtype
)->tp_name
, (long)length
);
4638 result
= PyObject_CallFunction((PyObject
*)&PyCArrayType_Type
,
4639 #if (PY_VERSION_HEX < 0x02050000)
4651 if (result
== NULL
) {
4655 if (-1 == PyDict_SetItemProxy(cache
, key
, result
)) {
4665 /******************************************************************/
4671 Simple_set_value(CDataObject
*self
, PyObject
*value
)
4674 StgDictObject
*dict
= PyObject_stgdict((PyObject
*)self
);
4676 if (value
== NULL
) {
4677 PyErr_SetString(PyExc_TypeError
,
4678 "can't delete attribute");
4681 assert(dict
); /* Cannot be NULL for CDataObject instances */
4682 assert(dict
->setfunc
);
4683 result
= dict
->setfunc(self
->b_ptr
, value
, dict
->size
);
4687 /* consumes the refcount the setfunc returns */
4688 return KeepRef(self
, 0, result
);
4692 Simple_init(CDataObject
*self
, PyObject
*args
, PyObject
*kw
)
4694 PyObject
*value
= NULL
;
4695 if (!PyArg_UnpackTuple(args
, "__init__", 0, 1, &value
))
4698 return Simple_set_value(self
, value
);
4703 Simple_get_value(CDataObject
*self
)
4705 StgDictObject
*dict
;
4706 dict
= PyObject_stgdict((PyObject
*)self
);
4707 assert(dict
); /* Cannot be NULL for CDataObject instances */
4708 assert(dict
->getfunc
);
4709 return dict
->getfunc(self
->b_ptr
, self
->b_size
);
4712 static PyGetSetDef Simple_getsets
[] = {
4713 { "value", (getter
)Simple_get_value
, (setter
)Simple_set_value
,
4714 "current value", NULL
},
4719 Simple_from_outparm(PyObject
*self
, PyObject
*args
)
4721 if (_ctypes_simple_instance((PyObject
*)Py_TYPE(self
))) {
4725 /* call stgdict->getfunc */
4726 return Simple_get_value((CDataObject
*)self
);
4729 static PyMethodDef Simple_methods
[] = {
4730 { "__ctypes_from_outparam__", Simple_from_outparm
, METH_NOARGS
, },
4734 static int Simple_nonzero(CDataObject
*self
)
4736 return memcmp(self
->b_ptr
, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self
->b_size
);
4739 static PyNumberMethods Simple_as_number
= {
4741 0, /* nb_subtract */
4742 0, /* nb_multiply */
4744 0, /* nb_remainder */
4747 0, /* nb_negative */
4748 0, /* nb_positive */
4749 0, /* nb_absolute */
4750 (inquiry
)Simple_nonzero
, /* nb_nonzero */
4753 /* "%s(%s)" % (self.__class__.__name__, self.value) */
4755 Simple_repr(CDataObject
*self
)
4757 PyObject
*val
, *name
, *args
, *result
;
4758 static PyObject
*format
;
4760 if (Py_TYPE(self
)->tp_base
!= &Simple_Type
) {
4761 return PyString_FromFormat("<%s object at %p>",
4762 Py_TYPE(self
)->tp_name
, self
);
4765 if (format
== NULL
) {
4766 format
= PyString_InternFromString("%s(%r)");
4771 val
= Simple_get_value(self
);
4775 name
= PyString_FromString(Py_TYPE(self
)->tp_name
);
4781 args
= PyTuple_Pack(2, name
, val
);
4787 result
= PyString_Format(format
, args
);
4792 static PyTypeObject Simple_Type
= {
4793 PyVarObject_HEAD_INIT(NULL
, 0)
4794 "_ctypes._SimpleCData",
4795 sizeof(CDataObject
), /* tp_basicsize */
4796 0, /* tp_itemsize */
4802 (reprfunc
)&Simple_repr
, /* tp_repr */
4803 &Simple_as_number
, /* tp_as_number */
4804 0, /* tp_as_sequence */
4805 0, /* tp_as_mapping */
4809 0, /* tp_getattro */
4810 0, /* tp_setattro */
4811 &PyCData_as_buffer
, /* tp_as_buffer */
4812 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_NEWBUFFER
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
4813 "XXX to be provided", /* tp_doc */
4814 (traverseproc
)PyCData_traverse
, /* tp_traverse */
4815 (inquiry
)PyCData_clear
, /* tp_clear */
4816 0, /* tp_richcompare */
4817 0, /* tp_weaklistoffset */
4819 0, /* tp_iternext */
4820 Simple_methods
, /* tp_methods */
4822 Simple_getsets
, /* tp_getset */
4825 0, /* tp_descr_get */
4826 0, /* tp_descr_set */
4827 0, /* tp_dictoffset */
4828 (initproc
)Simple_init
, /* tp_init */
4830 GenericPyCData_new
, /* tp_new */
4834 /******************************************************************/
4839 Pointer_item(PyObject
*_self
, Py_ssize_t index
)
4841 CDataObject
*self
= (CDataObject
*)_self
;
4844 StgDictObject
*stgdict
, *itemdict
;
4847 if (*(void **)self
->b_ptr
== NULL
) {
4848 PyErr_SetString(PyExc_ValueError
,
4849 "NULL pointer access");
4853 stgdict
= PyObject_stgdict((PyObject
*)self
);
4854 assert(stgdict
); /* Cannot be NULL for pointer object instances */
4856 proto
= stgdict
->proto
;
4858 itemdict
= PyType_stgdict(proto
);
4859 assert(itemdict
); /* proto is the item type of the pointer, a ctypes
4860 type, so this cannot be NULL */
4862 size
= itemdict
->size
;
4863 offset
= index
* itemdict
->size
;
4865 return PyCData_get(proto
, stgdict
->getfunc
, (PyObject
*)self
,
4866 index
, size
, (*(char **)self
->b_ptr
) + offset
);
4870 Pointer_ass_item(PyObject
*_self
, Py_ssize_t index
, PyObject
*value
)
4872 CDataObject
*self
= (CDataObject
*)_self
;
4875 StgDictObject
*stgdict
, *itemdict
;
4878 if (value
== NULL
) {
4879 PyErr_SetString(PyExc_TypeError
,
4880 "Pointer does not support item deletion");
4884 if (*(void **)self
->b_ptr
== NULL
) {
4885 PyErr_SetString(PyExc_ValueError
,
4886 "NULL pointer access");
4890 stgdict
= PyObject_stgdict((PyObject
*)self
);
4891 assert(stgdict
); /* Cannot be NULL fr pointer instances */
4893 proto
= stgdict
->proto
;
4896 itemdict
= PyType_stgdict(proto
);
4897 assert(itemdict
); /* Cannot be NULL because the itemtype of a pointer
4898 is always a ctypes type */
4900 size
= itemdict
->size
;
4901 offset
= index
* itemdict
->size
;
4903 return PyCData_set((PyObject
*)self
, proto
, stgdict
->setfunc
, value
,
4904 index
, size
, (*(char **)self
->b_ptr
) + offset
);
4908 Pointer_get_contents(CDataObject
*self
, void *closure
)
4910 StgDictObject
*stgdict
;
4912 if (*(void **)self
->b_ptr
== NULL
) {
4913 PyErr_SetString(PyExc_ValueError
,
4914 "NULL pointer access");
4918 stgdict
= PyObject_stgdict((PyObject
*)self
);
4919 assert(stgdict
); /* Cannot be NULL fr pointer instances */
4920 return PyCData_FromBaseObj(stgdict
->proto
,
4921 (PyObject
*)self
, 0,
4922 *(void **)self
->b_ptr
);
4926 Pointer_set_contents(CDataObject
*self
, PyObject
*value
, void *closure
)
4928 StgDictObject
*stgdict
;
4932 if (value
== NULL
) {
4933 PyErr_SetString(PyExc_TypeError
,
4934 "Pointer does not support item deletion");
4937 stgdict
= PyObject_stgdict((PyObject
*)self
);
4938 assert(stgdict
); /* Cannot be NULL fr pointer instances */
4939 assert(stgdict
->proto
);
4940 if (!CDataObject_Check(value
)
4941 || 0 == PyObject_IsInstance(value
, stgdict
->proto
)) {
4942 /* XXX PyObject_IsInstance could return -1! */
4943 PyErr_Format(PyExc_TypeError
,
4944 "expected %s instead of %s",
4945 ((PyTypeObject
*)(stgdict
->proto
))->tp_name
,
4946 Py_TYPE(value
)->tp_name
);
4950 dst
= (CDataObject
*)value
;
4951 *(void **)self
->b_ptr
= dst
->b_ptr
;
4954 A Pointer instance must keep a the value it points to alive. So, a
4955 pointer instance has b_length set to 2 instead of 1, and we set
4956 'value' itself as the second item of the b_objects list, additionally.
4959 if (-1 == KeepRef(self
, 1, value
))
4962 keep
= GetKeepedObjects(dst
);
4964 return KeepRef(self
, 0, keep
);
4967 static PyGetSetDef Pointer_getsets
[] = {
4968 { "contents", (getter
)Pointer_get_contents
,
4969 (setter
)Pointer_set_contents
,
4970 "the object this pointer points to (read-write)", NULL
},
4975 Pointer_init(CDataObject
*self
, PyObject
*args
, PyObject
*kw
)
4977 PyObject
*value
= NULL
;
4979 if (!PyArg_UnpackTuple(args
, "POINTER", 0, 1, &value
))
4983 return Pointer_set_contents(self
, value
, NULL
);
4987 Pointer_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kw
)
4989 StgDictObject
*dict
= PyType_stgdict((PyObject
*)type
);
4990 if (!dict
|| !dict
->proto
) {
4991 PyErr_SetString(PyExc_TypeError
,
4992 "Cannot create instance: has no _type_");
4995 return GenericPyCData_new(type
, args
, kw
);
4999 Pointer_slice(PyObject
*_self
, Py_ssize_t ilow
, Py_ssize_t ihigh
)
5001 CDataObject
*self
= (CDataObject
*)_self
;
5003 StgDictObject
*stgdict
, *itemdict
;
5013 stgdict
= PyObject_stgdict((PyObject
*)self
);
5014 assert(stgdict
); /* Cannot be NULL fr pointer instances */
5015 proto
= stgdict
->proto
;
5017 itemdict
= PyType_stgdict(proto
);
5019 if (itemdict
->getfunc
== _ctypes_get_fielddesc("c")->getfunc
) {
5020 char *ptr
= *(char **)self
->b_ptr
;
5021 return PyString_FromStringAndSize(ptr
+ ilow
, len
);
5022 #ifdef CTYPES_UNICODE
5023 } else if (itemdict
->getfunc
== _ctypes_get_fielddesc("u")->getfunc
) {
5024 wchar_t *ptr
= *(wchar_t **)self
->b_ptr
;
5025 return PyUnicode_FromWideChar(ptr
+ ilow
, len
);
5029 np
= (PyListObject
*) PyList_New(len
);
5033 for (i
= 0; i
< len
; i
++) {
5034 PyObject
*v
= Pointer_item(_self
, i
+ilow
);
5035 PyList_SET_ITEM(np
, i
, v
);
5037 return (PyObject
*)np
;
5041 Pointer_subscript(PyObject
*_self
, PyObject
*item
)
5043 CDataObject
*self
= (CDataObject
*)_self
;
5044 if (PyIndex_Check(item
)) {
5045 Py_ssize_t i
= PyNumber_AsSsize_t(item
, PyExc_IndexError
);
5046 if (i
== -1 && PyErr_Occurred())
5048 return Pointer_item(_self
, i
);
5050 else if (PySlice_Check(item
)) {
5051 PySliceObject
*slice
= (PySliceObject
*)item
;
5052 Py_ssize_t start
, stop
, step
;
5054 StgDictObject
*stgdict
, *itemdict
;
5056 Py_ssize_t i
, len
, cur
;
5058 /* Since pointers have no length, and we want to apply
5059 different semantics to negative indices than normal
5060 slicing, we have to dissect the slice object ourselves.*/
5061 if (slice
->step
== Py_None
) {
5065 step
= PyNumber_AsSsize_t(slice
->step
,
5067 if (step
== -1 && PyErr_Occurred())
5070 PyErr_SetString(PyExc_ValueError
,
5071 "slice step cannot be zero");
5075 if (slice
->start
== Py_None
) {
5077 PyErr_SetString(PyExc_ValueError
,
5078 "slice start is required "
5085 start
= PyNumber_AsSsize_t(slice
->start
,
5087 if (start
== -1 && PyErr_Occurred())
5090 if (slice
->stop
== Py_None
) {
5091 PyErr_SetString(PyExc_ValueError
,
5092 "slice stop is required");
5095 stop
= PyNumber_AsSsize_t(slice
->stop
,
5097 if (stop
== -1 && PyErr_Occurred())
5099 if ((step
> 0 && start
> stop
) ||
5100 (step
< 0 && start
< stop
))
5103 len
= (stop
- start
- 1) / step
+ 1;
5105 len
= (stop
- start
+ 1) / step
+ 1;
5107 stgdict
= PyObject_stgdict((PyObject
*)self
);
5108 assert(stgdict
); /* Cannot be NULL for pointer instances */
5109 proto
= stgdict
->proto
;
5111 itemdict
= PyType_stgdict(proto
);
5113 if (itemdict
->getfunc
== _ctypes_get_fielddesc("c")->getfunc
) {
5114 char *ptr
= *(char **)self
->b_ptr
;
5118 return PyString_FromString("");
5120 return PyString_FromStringAndSize(ptr
+ start
,
5123 dest
= (char *)PyMem_Malloc(len
);
5125 return PyErr_NoMemory();
5126 for (cur
= start
, i
= 0; i
< len
; cur
+= step
, i
++) {
5129 np
= PyString_FromStringAndSize(dest
, len
);
5133 #ifdef CTYPES_UNICODE
5134 if (itemdict
->getfunc
== _ctypes_get_fielddesc("u")->getfunc
) {
5135 wchar_t *ptr
= *(wchar_t **)self
->b_ptr
;
5139 return PyUnicode_FromUnicode(NULL
, 0);
5141 return PyUnicode_FromWideChar(ptr
+ start
,
5144 dest
= (wchar_t *)PyMem_Malloc(len
* sizeof(wchar_t));
5146 return PyErr_NoMemory();
5147 for (cur
= start
, i
= 0; i
< len
; cur
+= step
, i
++) {
5150 np
= PyUnicode_FromWideChar(dest
, len
);
5156 np
= PyList_New(len
);
5160 for (cur
= start
, i
= 0; i
< len
; cur
+= step
, i
++) {
5161 PyObject
*v
= Pointer_item(_self
, cur
);
5162 PyList_SET_ITEM(np
, i
, v
);
5167 PyErr_SetString(PyExc_TypeError
,
5168 "Pointer indices must be integer");
5173 static PySequenceMethods Pointer_as_sequence
= {
5174 0, /* inquiry sq_length; */
5175 0, /* binaryfunc sq_concat; */
5176 0, /* intargfunc sq_repeat; */
5177 Pointer_item
, /* intargfunc sq_item; */
5178 Pointer_slice
, /* intintargfunc sq_slice; */
5179 Pointer_ass_item
, /* intobjargproc sq_ass_item; */
5180 0, /* intintobjargproc sq_ass_slice; */
5181 0, /* objobjproc sq_contains; */
5182 /* Added in release 2.0 */
5183 0, /* binaryfunc sq_inplace_concat; */
5184 0, /* intargfunc sq_inplace_repeat; */
5187 static PyMappingMethods Pointer_as_mapping
= {
5193 Pointer_nonzero(CDataObject
*self
)
5195 return (*(void **)self
->b_ptr
!= NULL
);
5198 static PyNumberMethods Pointer_as_number
= {
5200 0, /* nb_subtract */
5201 0, /* nb_multiply */
5203 0, /* nb_remainder */
5206 0, /* nb_negative */
5207 0, /* nb_positive */
5208 0, /* nb_absolute */
5209 (inquiry
)Pointer_nonzero
, /* nb_nonzero */
5212 PyTypeObject PyCPointer_Type
= {
5213 PyVarObject_HEAD_INIT(NULL
, 0)
5215 sizeof(CDataObject
), /* tp_basicsize */
5216 0, /* tp_itemsize */
5223 &Pointer_as_number
, /* tp_as_number */
5224 &Pointer_as_sequence
, /* tp_as_sequence */
5225 &Pointer_as_mapping
, /* tp_as_mapping */
5229 0, /* tp_getattro */
5230 0, /* tp_setattro */
5231 &PyCData_as_buffer
, /* tp_as_buffer */
5232 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_NEWBUFFER
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
5233 "XXX to be provided", /* tp_doc */
5234 (traverseproc
)PyCData_traverse
, /* tp_traverse */
5235 (inquiry
)PyCData_clear
, /* tp_clear */
5236 0, /* tp_richcompare */
5237 0, /* tp_weaklistoffset */
5239 0, /* tp_iternext */
5242 Pointer_getsets
, /* tp_getset */
5245 0, /* tp_descr_get */
5246 0, /* tp_descr_set */
5247 0, /* tp_dictoffset */
5248 (initproc
)Pointer_init
, /* tp_init */
5250 Pointer_new
, /* tp_new */
5255 /******************************************************************/
5257 * Module initialization.
5260 static char *module_docs
=
5261 "Create and manipulate C compatible data types in Python.";
5265 static char comerror_doc
[] = "Raised when a COM method call failed.";
5268 comerror_init(PyObject
*self
, PyObject
*args
)
5270 PyObject
*hresult
, *text
, *details
;
5274 if (!PyArg_ParseTuple(args
, "OOOO:COMError", &self
, &hresult
, &text
, &details
))
5277 a
= PySequence_GetSlice(args
, 1, PySequence_Size(args
));
5280 status
= PyObject_SetAttrString(self
, "args", a
);
5285 if (PyObject_SetAttrString(self
, "hresult", hresult
) < 0)
5288 if (PyObject_SetAttrString(self
, "text", text
) < 0)
5291 if (PyObject_SetAttrString(self
, "details", details
) < 0)
5298 static PyMethodDef comerror_methods
[] = {
5299 { "__init__", comerror_init
, METH_VARARGS
},
5304 create_comerror(void)
5306 PyObject
*dict
= PyDict_New();
5307 PyMethodDef
*methods
= comerror_methods
;
5314 while (methods
->ml_name
) {
5315 /* get a wrapper for the built-in function */
5316 PyObject
*func
= PyCFunction_New(methods
, NULL
);
5320 meth
= PyMethod_New(func
, NULL
, ComError
);
5324 PyDict_SetItemString(dict
, methods
->ml_name
, meth
);
5329 s
= PyString_FromString(comerror_doc
);
5332 status
= PyDict_SetItemString(dict
, "__doc__", s
);
5337 ComError
= PyErr_NewException("_ctypes.COMError",
5340 if (ComError
== NULL
)
5352 string_at(const char *ptr
, int size
)
5355 return PyString_FromString(ptr
);
5356 return PyString_FromStringAndSize(ptr
, size
);
5360 cast_check_pointertype(PyObject
*arg
)
5362 StgDictObject
*dict
;
5364 if (PyCPointerTypeObject_Check(arg
))
5366 if (PyCFuncPtrTypeObject_Check(arg
))
5368 dict
= PyType_stgdict(arg
);
5370 if (PyString_Check(dict
->proto
)
5371 && (strchr("sPzUZXO", PyString_AS_STRING(dict
->proto
)[0]))) {
5372 /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
5376 PyErr_Format(PyExc_TypeError
,
5377 "cast() argument 2 must be a pointer type, not %s",
5379 ? ((PyTypeObject
*)arg
)->tp_name
5380 : Py_TYPE(arg
)->tp_name
);
5385 cast(void *ptr
, PyObject
*src
, PyObject
*ctype
)
5387 CDataObject
*result
;
5388 if (0 == cast_check_pointertype(ctype
))
5390 result
= (CDataObject
*)PyObject_CallFunctionObjArgs(ctype
, NULL
);
5395 The casted objects '_objects' member:
5397 It must certainly contain the source objects one.
5398 It must contain the source object itself.
5400 if (CDataObject_Check(src
)) {
5401 CDataObject
*obj
= (CDataObject
*)src
;
5402 /* PyCData_GetContainer will initialize src.b_objects, we need
5403 this so it can be shared */
5404 PyCData_GetContainer(obj
);
5405 /* But we need a dictionary! */
5406 if (obj
->b_objects
== Py_None
) {
5408 obj
->b_objects
= PyDict_New();
5409 if (obj
->b_objects
== NULL
)
5412 Py_XINCREF(obj
->b_objects
);
5413 result
->b_objects
= obj
->b_objects
;
5414 if (result
->b_objects
&& PyDict_CheckExact(result
->b_objects
)) {
5417 index
= PyLong_FromVoidPtr((void *)src
);
5420 rc
= PyDict_SetItem(result
->b_objects
, index
, src
);
5426 /* Should we assert that result is a pointer type? */
5427 memcpy(result
->b_ptr
, &ptr
, sizeof(void *));
5428 return (PyObject
*)result
;
5435 #ifdef CTYPES_UNICODE
5437 wstring_at(const wchar_t *ptr
, int size
)
5439 Py_ssize_t ssize
= size
;
5441 ssize
= wcslen(ptr
);
5442 return PyUnicode_FromWideChar(ptr
, ssize
);
5452 ob_type is the metatype (the 'type'), defaults to PyType_Type,
5453 tp_base is the base type, defaults to 'object' aka PyBaseObject_Type.
5456 PyEval_InitThreads();
5458 m
= Py_InitModule3("_ctypes", _ctypes_module_methods
, module_docs
);
5462 _ctypes_ptrtype_cache
= PyDict_New();
5463 if (_ctypes_ptrtype_cache
== NULL
)
5466 PyModule_AddObject(m
, "_pointer_type_cache", (PyObject
*)_ctypes_ptrtype_cache
);
5468 _unpickle
= PyObject_GetAttrString(m
, "_unpickle");
5469 if (_unpickle
== NULL
)
5472 if (PyType_Ready(&PyCArg_Type
) < 0)
5475 if (PyType_Ready(&PyCThunk_Type
) < 0)
5478 /* StgDict is derived from PyDict_Type */
5479 PyCStgDict_Type
.tp_base
= &PyDict_Type
;
5480 if (PyType_Ready(&PyCStgDict_Type
) < 0)
5483 /*************************************************
5488 PyCStructType_Type
.tp_base
= &PyType_Type
;
5489 if (PyType_Ready(&PyCStructType_Type
) < 0)
5492 UnionType_Type
.tp_base
= &PyType_Type
;
5493 if (PyType_Ready(&UnionType_Type
) < 0)
5496 PyCPointerType_Type
.tp_base
= &PyType_Type
;
5497 if (PyType_Ready(&PyCPointerType_Type
) < 0)
5500 PyCArrayType_Type
.tp_base
= &PyType_Type
;
5501 if (PyType_Ready(&PyCArrayType_Type
) < 0)
5504 PyCSimpleType_Type
.tp_base
= &PyType_Type
;
5505 if (PyType_Ready(&PyCSimpleType_Type
) < 0)
5508 PyCFuncPtrType_Type
.tp_base
= &PyType_Type
;
5509 if (PyType_Ready(&PyCFuncPtrType_Type
) < 0)
5512 /*************************************************
5514 * Classes using a custom metaclass
5517 if (PyType_Ready(&PyCData_Type
) < 0)
5520 Py_TYPE(&Struct_Type
) = &PyCStructType_Type
;
5521 Struct_Type
.tp_base
= &PyCData_Type
;
5522 if (PyType_Ready(&Struct_Type
) < 0)
5524 PyModule_AddObject(m
, "Structure", (PyObject
*)&Struct_Type
);
5526 Py_TYPE(&Union_Type
) = &UnionType_Type
;
5527 Union_Type
.tp_base
= &PyCData_Type
;
5528 if (PyType_Ready(&Union_Type
) < 0)
5530 PyModule_AddObject(m
, "Union", (PyObject
*)&Union_Type
);
5532 Py_TYPE(&PyCPointer_Type
) = &PyCPointerType_Type
;
5533 PyCPointer_Type
.tp_base
= &PyCData_Type
;
5534 if (PyType_Ready(&PyCPointer_Type
) < 0)
5536 PyModule_AddObject(m
, "_Pointer", (PyObject
*)&PyCPointer_Type
);
5538 Py_TYPE(&PyCArray_Type
) = &PyCArrayType_Type
;
5539 PyCArray_Type
.tp_base
= &PyCData_Type
;
5540 if (PyType_Ready(&PyCArray_Type
) < 0)
5542 PyModule_AddObject(m
, "Array", (PyObject
*)&PyCArray_Type
);
5544 Py_TYPE(&Simple_Type
) = &PyCSimpleType_Type
;
5545 Simple_Type
.tp_base
= &PyCData_Type
;
5546 if (PyType_Ready(&Simple_Type
) < 0)
5548 PyModule_AddObject(m
, "_SimpleCData", (PyObject
*)&Simple_Type
);
5550 Py_TYPE(&PyCFuncPtr_Type
) = &PyCFuncPtrType_Type
;
5551 PyCFuncPtr_Type
.tp_base
= &PyCData_Type
;
5552 if (PyType_Ready(&PyCFuncPtr_Type
) < 0)
5554 PyModule_AddObject(m
, "CFuncPtr", (PyObject
*)&PyCFuncPtr_Type
);
5556 /*************************************************
5561 /* PyCField_Type is derived from PyBaseObject_Type */
5562 if (PyType_Ready(&PyCField_Type
) < 0)
5565 /*************************************************
5570 DictRemover_Type
.tp_new
= PyType_GenericNew
;
5571 if (PyType_Ready(&DictRemover_Type
) < 0)
5575 if (create_comerror() < 0)
5577 PyModule_AddObject(m
, "COMError", ComError
);
5579 PyModule_AddObject(m
, "FUNCFLAG_HRESULT", PyInt_FromLong(FUNCFLAG_HRESULT
));
5580 PyModule_AddObject(m
, "FUNCFLAG_STDCALL", PyInt_FromLong(FUNCFLAG_STDCALL
));
5582 PyModule_AddObject(m
, "FUNCFLAG_CDECL", PyInt_FromLong(FUNCFLAG_CDECL
));
5583 PyModule_AddObject(m
, "FUNCFLAG_USE_ERRNO", PyInt_FromLong(FUNCFLAG_USE_ERRNO
));
5584 PyModule_AddObject(m
, "FUNCFLAG_USE_LASTERROR", PyInt_FromLong(FUNCFLAG_USE_LASTERROR
));
5585 PyModule_AddObject(m
, "FUNCFLAG_PYTHONAPI", PyInt_FromLong(FUNCFLAG_PYTHONAPI
));
5586 PyModule_AddStringConstant(m
, "__version__", "1.1.0");
5588 PyModule_AddObject(m
, "_memmove_addr", PyLong_FromVoidPtr(memmove
));
5589 PyModule_AddObject(m
, "_memset_addr", PyLong_FromVoidPtr(memset
));
5590 PyModule_AddObject(m
, "_string_at_addr", PyLong_FromVoidPtr(string_at
));
5591 PyModule_AddObject(m
, "_cast_addr", PyLong_FromVoidPtr(cast
));
5592 #ifdef CTYPES_UNICODE
5593 PyModule_AddObject(m
, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at
));
5596 /* If RTLD_LOCAL is not defined (Windows!), set it to zero. */
5598 #define RTLD_LOCAL 0
5601 /* If RTLD_GLOBAL is not defined (cygwin), set it to the same value as
5605 #define RTLD_GLOBAL RTLD_LOCAL
5608 PyModule_AddObject(m
, "RTLD_LOCAL", PyInt_FromLong(RTLD_LOCAL
));
5609 PyModule_AddObject(m
, "RTLD_GLOBAL", PyInt_FromLong(RTLD_GLOBAL
));
5611 PyExc_ArgError
= PyErr_NewException("ctypes.ArgumentError", NULL
, NULL
);
5612 if (PyExc_ArgError
) {
5613 Py_INCREF(PyExc_ArgError
);
5614 PyModule_AddObject(m
, "ArgumentError", PyExc_ArgError
);
5618 /*****************************************************************
5619 * replacements for broken Python api functions (in Python 2.3).
5620 * See #1047269 Buffer overwrite in PyUnicode_AsWideChar
5623 #if (PY_VERSION_HEX < 0x02040000)
5626 PyObject
*My_PyUnicode_FromWideChar(register const wchar_t *w
,
5629 PyUnicodeObject
*unicode
;
5632 PyErr_BadInternalCall();
5636 unicode
= (PyUnicodeObject
*)PyUnicode_FromUnicode(NULL
, size
);
5640 /* Copy the wchar_t data into the new object */
5641 #ifdef HAVE_USABLE_WCHAR_T
5642 memcpy(unicode
->str
, w
, size
* sizeof(wchar_t));
5645 register Py_UNICODE
*u
;
5647 u
= PyUnicode_AS_UNICODE(unicode
);
5648 /* In Python, the following line has a one-off error */
5649 for (i
= size
; i
> 0; i
--)
5654 return (PyObject
*)unicode
;
5657 Py_ssize_t
My_PyUnicode_AsWideChar(PyUnicodeObject
*unicode
,
5658 register wchar_t *w
,
5661 if (unicode
== NULL
) {
5662 PyErr_BadInternalCall();
5665 if (size
> PyUnicode_GET_SIZE(unicode
))
5666 size
= PyUnicode_GET_SIZE(unicode
);
5667 #ifdef HAVE_USABLE_WCHAR_T
5668 memcpy(w
, unicode
->str
, size
* sizeof(wchar_t));
5671 register Py_UNICODE
*u
;
5673 u
= PyUnicode_AS_UNICODE(unicode
);
5674 /* In Python, the following line has a one-off error */
5675 for (i
= size
; i
> 0; i
--)
5687 compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"