Home | History | Annotate | Download | only in _ctypes
      1 /*
      2   ToDo:
      3 
      4   Get rid of the checker (and also the converters) field in PyCFuncPtrObject and
      5   StgDictObject, and replace them by slot functions in StgDictObject.
      6 
      7   think about a buffer-like object (memory? bytes?)
      8 
      9   Should POINTER(c_char) and POINTER(c_wchar) have a .value property?
     10   What about c_char and c_wchar arrays then?
     11 
     12   Add from_mmap, from_file, from_string metaclass methods.
     13 
     14   Maybe we can get away with from_file (calls read) and with a from_buffer
     15   method?
     16 
     17   And what about the to_mmap, to_file, to_str(?) methods?  They would clobber
     18   the namespace, probably. So, functions instead? And we already have memmove...
     19 */
     20 
     21 /*
     22 
     23 Name                    methods, members, getsets
     24 ==============================================================================
     25 
     26 PyCStructType_Type              __new__(), from_address(), __mul__(), from_param()
     27 UnionType_Type          __new__(), from_address(), __mul__(), from_param()
     28 PyCPointerType_Type     __new__(), from_address(), __mul__(), from_param(), set_type()
     29 PyCArrayType_Type               __new__(), from_address(), __mul__(), from_param()
     30 PyCSimpleType_Type              __new__(), from_address(), __mul__(), from_param()
     31 
     32 PyCData_Type
     33   Struct_Type           __new__(), __init__()
     34   PyCPointer_Type               __new__(), __init__(), _as_parameter_, contents
     35   PyCArray_Type         __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__()
     36   Simple_Type           __new__(), __init__(), _as_parameter_
     37 
     38 PyCField_Type
     39 PyCStgDict_Type
     40 
     41 ==============================================================================
     42 
     43 class methods
     44 -------------
     45 
     46 It has some similarity to the byref() construct compared to pointer()
     47 from_address(addr)
     48     - construct an instance from a given memory block (sharing this memory block)
     49 
     50 from_param(obj)
     51     - typecheck and convert a Python object into a C function call parameter
     52       The result may be an instance of the type, or an integer or tuple
     53       (typecode, value[, obj])
     54 
     55 instance methods/properties
     56 ---------------------------
     57 
     58 _as_parameter_
     59     - convert self into a C function call parameter
     60       This is either an integer, or a 3-tuple (typecode, value, obj)
     61 
     62 functions
     63 ---------
     64 
     65 sizeof(cdata)
     66     - return the number of bytes the buffer contains
     67 
     68 sizeof(ctype)
     69     - return the number of bytes the buffer of an instance would contain
     70 
     71 byref(cdata)
     72 
     73 addressof(cdata)
     74 
     75 pointer(cdata)
     76 
     77 POINTER(ctype)
     78 
     79 bytes(cdata)
     80     - return the buffer contents as a sequence of bytes (which is currently a string)
     81 
     82 */
     83 
     84 /*
     85  * PyCStgDict_Type
     86  * PyCStructType_Type
     87  * UnionType_Type
     88  * PyCPointerType_Type
     89  * PyCArrayType_Type
     90  * PyCSimpleType_Type
     91  *
     92  * PyCData_Type
     93  * Struct_Type
     94  * Union_Type
     95  * PyCArray_Type
     96  * Simple_Type
     97  * PyCPointer_Type
     98  * PyCField_Type
     99  *
    100  */
    101 
    102 #define PY_SSIZE_T_CLEAN
    103 
    104 #include "Python.h"
    105 #include "structmember.h"
    106 
    107 #include <ffi.h>
    108 #ifdef MS_WIN32
    109 #include <windows.h>
    110 #include <malloc.h>
    111 #ifndef IS_INTRESOURCE
    112 #define IS_INTRESOURCE(x) (((size_t)(x) >> 16) == 0)
    113 #endif
    114 #else
    115 #include "ctypes_dlfcn.h"
    116 #endif
    117 #include "ctypes.h"
    118 
    119 PyObject *PyExc_ArgError;
    120 
    121 /* This dict maps ctypes types to POINTER types */
    122 PyObject *_ctypes_ptrtype_cache;
    123 
    124 static PyTypeObject Simple_Type;
    125 
    126 /* a callable object used for unpickling */
    127 static PyObject *_unpickle;
    128 
    129 
    130 
    131 /****************************************************************/
    132 
    133 typedef struct {
    134     PyObject_HEAD
    135     PyObject *key;
    136     PyObject *dict;
    137 } DictRemoverObject;
    138 
    139 static void
    140 _DictRemover_dealloc(PyObject *myself)
    141 {
    142     DictRemoverObject *self = (DictRemoverObject *)myself;
    143     Py_XDECREF(self->key);
    144     Py_XDECREF(self->dict);
    145     Py_TYPE(self)->tp_free(myself);
    146 }
    147 
    148 static PyObject *
    149 _DictRemover_call(PyObject *myself, PyObject *args, PyObject *kw)
    150 {
    151     DictRemoverObject *self = (DictRemoverObject *)myself;
    152     if (self->key && self->dict) {
    153         if (-1 == PyDict_DelItem(self->dict, self->key))
    154             /* XXX Error context */
    155             PyErr_WriteUnraisable(Py_None);
    156         Py_CLEAR(self->key);
    157         Py_CLEAR(self->dict);
    158     }
    159     Py_INCREF(Py_None);
    160     return Py_None;
    161 }
    162 
    163 static PyTypeObject DictRemover_Type = {
    164     PyVarObject_HEAD_INIT(NULL, 0)
    165     "_ctypes.DictRemover",                      /* tp_name */
    166     sizeof(DictRemoverObject),                  /* tp_basicsize */
    167     0,                                          /* tp_itemsize */
    168     _DictRemover_dealloc,                       /* tp_dealloc */
    169     0,                                          /* tp_print */
    170     0,                                          /* tp_getattr */
    171     0,                                          /* tp_setattr */
    172     0,                                          /* tp_reserved */
    173     0,                                          /* tp_repr */
    174     0,                                          /* tp_as_number */
    175     0,                                          /* tp_as_sequence */
    176     0,                                          /* tp_as_mapping */
    177     0,                                          /* tp_hash */
    178     _DictRemover_call,                          /* tp_call */
    179     0,                                          /* tp_str */
    180     0,                                          /* tp_getattro */
    181     0,                                          /* tp_setattro */
    182     0,                                          /* tp_as_buffer */
    183 /* XXX should participate in GC? */
    184     Py_TPFLAGS_DEFAULT,                         /* tp_flags */
    185     "deletes a key from a dictionary",          /* tp_doc */
    186     0,                                          /* tp_traverse */
    187     0,                                          /* tp_clear */
    188     0,                                          /* tp_richcompare */
    189     0,                                          /* tp_weaklistoffset */
    190     0,                                          /* tp_iter */
    191     0,                                          /* tp_iternext */
    192     0,                                          /* tp_methods */
    193     0,                                          /* tp_members */
    194     0,                                          /* tp_getset */
    195     0,                                          /* tp_base */
    196     0,                                          /* tp_dict */
    197     0,                                          /* tp_descr_get */
    198     0,                                          /* tp_descr_set */
    199     0,                                          /* tp_dictoffset */
    200     0,                                          /* tp_init */
    201     0,                                          /* tp_alloc */
    202     0,                                          /* tp_new */
    203     0,                                          /* tp_free */
    204 };
    205 
    206 int
    207 PyDict_SetItemProxy(PyObject *dict, PyObject *key, PyObject *item)
    208 {
    209     PyObject *obj;
    210     DictRemoverObject *remover;
    211     PyObject *proxy;
    212     int result;
    213 
    214     obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL);
    215     if (obj == NULL)
    216         return -1;
    217 
    218     remover = (DictRemoverObject *)obj;
    219     assert(remover->key == NULL);
    220     assert(remover->dict == NULL);
    221     Py_INCREF(key);
    222     remover->key = key;
    223     Py_INCREF(dict);
    224     remover->dict = dict;
    225 
    226     proxy = PyWeakref_NewProxy(item, obj);
    227     Py_DECREF(obj);
    228     if (proxy == NULL)
    229         return -1;
    230 
    231     result = PyDict_SetItem(dict, key, proxy);
    232     Py_DECREF(proxy);
    233     return result;
    234 }
    235 
    236 PyObject *
    237 PyDict_GetItemProxy(PyObject *dict, PyObject *key)
    238 {
    239     PyObject *result;
    240     PyObject *item = PyDict_GetItem(dict, key);
    241 
    242     if (item == NULL)
    243         return NULL;
    244     if (!PyWeakref_CheckProxy(item))
    245         return item;
    246     result = PyWeakref_GET_OBJECT(item);
    247     if (result == Py_None)
    248         return NULL;
    249     return result;
    250 }
    251 
    252 /******************************************************************/
    253 /*
    254   Allocate a memory block for a pep3118 format string, copy prefix (if
    255   non-null) and suffix into it.  Returns NULL on failure, with the error
    256   indicator set.  If called with a suffix of NULL the error indicator must
    257   already be set.
    258  */
    259 char *
    260 _ctypes_alloc_format_string(const char *prefix, const char *suffix)
    261 {
    262     size_t len;
    263     char *result;
    264 
    265     if (suffix == NULL) {
    266         assert(PyErr_Occurred());
    267         return NULL;
    268     }
    269     len = strlen(suffix);
    270     if (prefix)
    271         len += strlen(prefix);
    272     result = PyMem_Malloc(len + 1);
    273     if (result == NULL) {
    274         PyErr_NoMemory();
    275         return NULL;
    276     }
    277     if (prefix)
    278         strcpy(result, prefix);
    279     else
    280         result[0] = '\0';
    281     strcat(result, suffix);
    282     return result;
    283 }
    284 
    285 /*
    286   Allocate a memory block for a pep3118 format string, adding
    287   the given prefix (if non-null), an additional shape prefix, and a suffix.
    288   Returns NULL on failure, with the error indicator set.  If called with
    289   a suffix of NULL the error indicator must already be set.
    290  */
    291 char *
    292 _ctypes_alloc_format_string_with_shape(int ndim, const Py_ssize_t *shape,
    293                                        const char *prefix, const char *suffix)
    294 {
    295     char *new_prefix;
    296     char *result;
    297     char buf[32];
    298     Py_ssize_t prefix_len;
    299     int k;
    300 
    301     prefix_len = 32 * ndim + 3;
    302     if (prefix)
    303         prefix_len += strlen(prefix);
    304     new_prefix = PyMem_Malloc(prefix_len);
    305     if (new_prefix == NULL)
    306         return NULL;
    307     new_prefix[0] = '\0';
    308     if (prefix)
    309         strcpy(new_prefix, prefix);
    310     if (ndim > 0) {
    311         /* Add the prefix "(shape[0],shape[1],...,shape[ndim-1])" */
    312         strcat(new_prefix, "(");
    313         for (k = 0; k < ndim; ++k) {
    314             if (k < ndim-1) {
    315                 sprintf(buf, "%"PY_FORMAT_SIZE_T"d,", shape[k]);
    316             } else {
    317                 sprintf(buf, "%"PY_FORMAT_SIZE_T"d)", shape[k]);
    318             }
    319             strcat(new_prefix, buf);
    320         }
    321     }
    322     result = _ctypes_alloc_format_string(new_prefix, suffix);
    323     PyMem_Free(new_prefix);
    324     return result;
    325 }
    326 
    327 /*
    328   PyCStructType_Type - a meta type/class.  Creating a new class using this one as
    329   __metaclass__ will call the constructor StructUnionType_new.  It replaces the
    330   tp_dict member with a new instance of StgDict, and initializes the C
    331   accessible fields somehow.
    332 */
    333 
    334 static PyCArgObject *
    335 StructUnionType_paramfunc(CDataObject *self)
    336 {
    337     PyCArgObject *parg;
    338     StgDictObject *stgdict;
    339 
    340     parg = PyCArgObject_new();
    341     if (parg == NULL)
    342         return NULL;
    343 
    344     parg->tag = 'V';
    345     stgdict = PyObject_stgdict((PyObject *)self);
    346     assert(stgdict); /* Cannot be NULL for structure/union instances */
    347     parg->pffi_type = &stgdict->ffi_type_pointer;
    348     /* For structure parameters (by value), parg->value doesn't contain the structure
    349        data itself, instead parg->value.p *points* to the structure's data
    350        See also _ctypes.c, function _call_function_pointer().
    351     */
    352     parg->value.p = self->b_ptr;
    353     parg->size = self->b_size;
    354     Py_INCREF(self);
    355     parg->obj = (PyObject *)self;
    356     return parg;
    357 }
    358 
    359 static PyObject *
    360 StructUnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds, int isStruct)
    361 {
    362     PyTypeObject *result;
    363     PyObject *fields;
    364     StgDictObject *dict;
    365 
    366     /* create the new instance (which is a class,
    367        since we are a metatype!) */
    368     result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
    369     if (!result)
    370         return NULL;
    371 
    372     /* keep this for bw compatibility */
    373     if (PyDict_GetItemString(result->tp_dict, "_abstract_"))
    374         return (PyObject *)result;
    375 
    376     dict = (StgDictObject *)PyObject_CallObject((PyObject *)&PyCStgDict_Type, NULL);
    377     if (!dict) {
    378         Py_DECREF(result);
    379         return NULL;
    380     }
    381     /* replace the class dict by our updated stgdict, which holds info
    382        about storage requirements of the instances */
    383     if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) {
    384         Py_DECREF(result);
    385         Py_DECREF((PyObject *)dict);
    386         return NULL;
    387     }
    388     Py_SETREF(result->tp_dict, (PyObject *)dict);
    389     dict->format = _ctypes_alloc_format_string(NULL, "B");
    390     if (dict->format == NULL) {
    391         Py_DECREF(result);
    392         return NULL;
    393     }
    394 
    395     dict->paramfunc = StructUnionType_paramfunc;
    396 
    397     fields = PyDict_GetItemString((PyObject *)dict, "_fields_");
    398     if (!fields) {
    399         StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base);
    400 
    401         if (basedict == NULL)
    402             return (PyObject *)result;
    403         /* copy base dict */
    404         if (-1 == PyCStgDict_clone(dict, basedict)) {
    405             Py_DECREF(result);
    406             return NULL;
    407         }
    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;
    411     }
    412 
    413     if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) {
    414         Py_DECREF(result);
    415         return NULL;
    416     }
    417     return (PyObject *)result;
    418 }
    419 
    420 static PyObject *
    421 PyCStructType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    422 {
    423     return StructUnionType_new(type, args, kwds, 1);
    424 }
    425 
    426 static PyObject *
    427 UnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    428 {
    429     return StructUnionType_new(type, args, kwds, 0);
    430 }
    431 
    432 static const char from_address_doc[] =
    433 "C.from_address(integer) -> C instance\naccess a C instance at the specified address";
    434 
    435 static PyObject *
    436 CDataType_from_address(PyObject *type, PyObject *value)
    437 {
    438     void *buf;
    439     if (!PyLong_Check(value)) {
    440         PyErr_SetString(PyExc_TypeError,
    441                         "integer expected");
    442         return NULL;
    443     }
    444     buf = (void *)PyLong_AsVoidPtr(value);
    445     if (PyErr_Occurred())
    446         return NULL;
    447     return PyCData_AtAddress(type, buf);
    448 }
    449 
    450 static const char from_buffer_doc[] =
    451 "C.from_buffer(object, offset=0) -> C instance\ncreate a C instance from a writeable buffer";
    452 
    453 static int
    454 KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep);
    455 
    456 static PyObject *
    457 CDataType_from_buffer(PyObject *type, PyObject *args)
    458 {
    459     PyObject *obj;
    460     PyObject *mv;
    461     PyObject *result;
    462     Py_buffer *buffer;
    463     Py_ssize_t offset = 0;
    464 
    465     StgDictObject *dict = PyType_stgdict(type);
    466     if (!dict) {
    467         PyErr_SetString(PyExc_TypeError, "abstract class");
    468         return NULL;
    469     }
    470 
    471     if (!PyArg_ParseTuple(args, "O|n:from_buffer", &obj, &offset))
    472         return NULL;
    473 
    474     mv = PyMemoryView_FromObject(obj);
    475     if (mv == NULL)
    476         return NULL;
    477 
    478     buffer = PyMemoryView_GET_BUFFER(mv);
    479 
    480     if (buffer->readonly) {
    481         PyErr_SetString(PyExc_TypeError,
    482             "underlying buffer is not writable");
    483         Py_DECREF(mv);
    484         return NULL;
    485     }
    486 
    487     if (!PyBuffer_IsContiguous(buffer, 'C')) {
    488         PyErr_SetString(PyExc_TypeError,
    489             "underlying buffer is not C contiguous");
    490         Py_DECREF(mv);
    491         return NULL;
    492     }
    493 
    494     if (offset < 0) {
    495         PyErr_SetString(PyExc_ValueError,
    496                         "offset cannot be negative");
    497         Py_DECREF(mv);
    498         return NULL;
    499     }
    500 
    501     if (dict->size > buffer->len - offset) {
    502         PyErr_Format(PyExc_ValueError,
    503                      "Buffer size too small "
    504                      "(%zd instead of at least %zd bytes)",
    505                      buffer->len, dict->size + offset);
    506         Py_DECREF(mv);
    507         return NULL;
    508     }
    509 
    510     result = PyCData_AtAddress(type, (char *)buffer->buf + offset);
    511     if (result == NULL) {
    512         Py_DECREF(mv);
    513         return NULL;
    514     }
    515 
    516     if (-1 == KeepRef((CDataObject *)result, -1, mv)) {
    517         Py_DECREF(result);
    518         return NULL;
    519     }
    520 
    521     return result;
    522 }
    523 
    524 static const char from_buffer_copy_doc[] =
    525 "C.from_buffer_copy(object, offset=0) -> C instance\ncreate a C instance from a readable buffer";
    526 
    527 static PyObject *
    528 GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
    529 
    530 static PyObject *
    531 CDataType_from_buffer_copy(PyObject *type, PyObject *args)
    532 {
    533     Py_buffer buffer;
    534     Py_ssize_t offset = 0;
    535     PyObject *result;
    536     StgDictObject *dict = PyType_stgdict(type);
    537     if (!dict) {
    538         PyErr_SetString(PyExc_TypeError, "abstract class");
    539         return NULL;
    540     }
    541 
    542     if (!PyArg_ParseTuple(args, "y*|n:from_buffer_copy", &buffer, &offset))
    543         return NULL;
    544 
    545     if (offset < 0) {
    546         PyErr_SetString(PyExc_ValueError,
    547                         "offset cannot be negative");
    548         PyBuffer_Release(&buffer);
    549         return NULL;
    550     }
    551 
    552     if (dict->size > buffer.len - offset) {
    553         PyErr_Format(PyExc_ValueError,
    554                      "Buffer size too small (%zd instead of at least %zd bytes)",
    555                      buffer.len, dict->size + offset);
    556         PyBuffer_Release(&buffer);
    557         return NULL;
    558     }
    559 
    560     result = GenericPyCData_new((PyTypeObject *)type, NULL, NULL);
    561     if (result != NULL) {
    562         memcpy(((CDataObject *)result)->b_ptr,
    563                (char *)buffer.buf + offset, dict->size);
    564     }
    565     PyBuffer_Release(&buffer);
    566     return result;
    567 }
    568 
    569 static const char in_dll_doc[] =
    570 "C.in_dll(dll, name) -> C instance\naccess a C instance in a dll";
    571 
    572 static PyObject *
    573 CDataType_in_dll(PyObject *type, PyObject *args)
    574 {
    575     PyObject *dll;
    576     char *name;
    577     PyObject *obj;
    578     void *handle;
    579     void *address;
    580 
    581     if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name))
    582         return NULL;
    583 
    584     obj = PyObject_GetAttrString(dll, "_handle");
    585     if (!obj)
    586         return NULL;
    587     if (!PyLong_Check(obj)) {
    588         PyErr_SetString(PyExc_TypeError,
    589                         "the _handle attribute of the second argument must be an integer");
    590         Py_DECREF(obj);
    591         return NULL;
    592     }
    593     handle = (void *)PyLong_AsVoidPtr(obj);
    594     Py_DECREF(obj);
    595     if (PyErr_Occurred()) {
    596         PyErr_SetString(PyExc_ValueError,
    597                         "could not convert the _handle attribute to a pointer");
    598         return NULL;
    599     }
    600 
    601 #ifdef MS_WIN32
    602     address = (void *)GetProcAddress(handle, name);
    603     if (!address) {
    604         PyErr_Format(PyExc_ValueError,
    605                      "symbol '%s' not found",
    606                      name);
    607         return NULL;
    608     }
    609 #else
    610     address = (void *)ctypes_dlsym(handle, name);
    611     if (!address) {
    612 #ifdef __CYGWIN__
    613 /* dlerror() isn't very helpful on cygwin */
    614         PyErr_Format(PyExc_ValueError,
    615                      "symbol '%s' not found",
    616                      name);
    617 #else
    618         PyErr_SetString(PyExc_ValueError, ctypes_dlerror());
    619 #endif
    620         return NULL;
    621     }
    622 #endif
    623     return PyCData_AtAddress(type, address);
    624 }
    625 
    626 static const char from_param_doc[] =
    627 "Convert a Python object into a function call parameter.";
    628 
    629 static PyObject *
    630 CDataType_from_param(PyObject *type, PyObject *value)
    631 {
    632     PyObject *as_parameter;
    633     int res = PyObject_IsInstance(value, type);
    634     if (res == -1)
    635         return NULL;
    636     if (res) {
    637         Py_INCREF(value);
    638         return value;
    639     }
    640     if (PyCArg_CheckExact(value)) {
    641         PyCArgObject *p = (PyCArgObject *)value;
    642         PyObject *ob = p->obj;
    643         const char *ob_name;
    644         StgDictObject *dict;
    645         dict = PyType_stgdict(type);
    646 
    647         /* If we got a PyCArgObject, we must check if the object packed in it
    648            is an instance of the type's dict->proto */
    649         if(dict && ob) {
    650             res = PyObject_IsInstance(ob, dict->proto);
    651             if (res == -1)
    652                 return NULL;
    653             if (res) {
    654                 Py_INCREF(value);
    655                 return value;
    656             }
    657         }
    658         ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???";
    659         PyErr_Format(PyExc_TypeError,
    660                      "expected %s instance instead of pointer to %s",
    661                      ((PyTypeObject *)type)->tp_name, ob_name);
    662         return NULL;
    663     }
    664 
    665     as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
    666     if (as_parameter) {
    667         value = CDataType_from_param(type, as_parameter);
    668         Py_DECREF(as_parameter);
    669         return value;
    670     }
    671     PyErr_Format(PyExc_TypeError,
    672                  "expected %s instance instead of %s",
    673                  ((PyTypeObject *)type)->tp_name,
    674                  Py_TYPE(value)->tp_name);
    675     return NULL;
    676 }
    677 
    678 static PyMethodDef CDataType_methods[] = {
    679     { "from_param", CDataType_from_param, METH_O, from_param_doc },
    680     { "from_address", CDataType_from_address, METH_O, from_address_doc },
    681     { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
    682     { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
    683     { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc },
    684     { NULL, NULL },
    685 };
    686 
    687 static PyObject *
    688 CDataType_repeat(PyObject *self, Py_ssize_t length)
    689 {
    690     if (length < 0)
    691         return PyErr_Format(PyExc_ValueError,
    692                             "Array length must be >= 0, not %zd",
    693                             length);
    694     return PyCArrayType_from_ctype(self, length);
    695 }
    696 
    697 static PySequenceMethods CDataType_as_sequence = {
    698     0,                          /* inquiry sq_length; */
    699     0,                          /* binaryfunc sq_concat; */
    700     CDataType_repeat,           /* intargfunc sq_repeat; */
    701     0,                          /* intargfunc sq_item; */
    702     0,                          /* intintargfunc sq_slice; */
    703     0,                          /* intobjargproc sq_ass_item; */
    704     0,                          /* intintobjargproc sq_ass_slice; */
    705     0,                          /* objobjproc sq_contains; */
    706 
    707     0,                          /* binaryfunc sq_inplace_concat; */
    708     0,                          /* intargfunc sq_inplace_repeat; */
    709 };
    710 
    711 static int
    712 CDataType_clear(PyTypeObject *self)
    713 {
    714     StgDictObject *dict = PyType_stgdict((PyObject *)self);
    715     if (dict)
    716         Py_CLEAR(dict->proto);
    717     return PyType_Type.tp_clear((PyObject *)self);
    718 }
    719 
    720 static int
    721 CDataType_traverse(PyTypeObject *self, visitproc visit, void *arg)
    722 {
    723     StgDictObject *dict = PyType_stgdict((PyObject *)self);
    724     if (dict)
    725         Py_VISIT(dict->proto);
    726     return PyType_Type.tp_traverse((PyObject *)self, visit, arg);
    727 }
    728 
    729 static int
    730 PyCStructType_setattro(PyObject *self, PyObject *key, PyObject *value)
    731 {
    732     /* XXX Should we disallow deleting _fields_? */
    733     if (-1 == PyType_Type.tp_setattro(self, key, value))
    734         return -1;
    735 
    736     if (value && PyUnicode_Check(key) &&
    737         _PyUnicode_EqualToASCIIString(key, "_fields_"))
    738         return PyCStructUnionType_update_stgdict(self, value, 1);
    739     return 0;
    740 }
    741 
    742 
    743 static int
    744 UnionType_setattro(PyObject *self, PyObject *key, PyObject *value)
    745 {
    746     /* XXX Should we disallow deleting _fields_? */
    747     if (-1 == PyObject_GenericSetAttr(self, key, value))
    748         return -1;
    749 
    750     if (PyUnicode_Check(key) &&
    751         _PyUnicode_EqualToASCIIString(key, "_fields_"))
    752         return PyCStructUnionType_update_stgdict(self, value, 0);
    753     return 0;
    754 }
    755 
    756 
    757 PyTypeObject PyCStructType_Type = {
    758     PyVarObject_HEAD_INIT(NULL, 0)
    759     "_ctypes.PyCStructType",                            /* tp_name */
    760     0,                                          /* tp_basicsize */
    761     0,                                          /* tp_itemsize */
    762     0,                                          /* tp_dealloc */
    763     0,                                          /* tp_print */
    764     0,                                          /* tp_getattr */
    765     0,                                          /* tp_setattr */
    766     0,                                          /* tp_reserved */
    767     0,                                          /* tp_repr */
    768     0,                                          /* tp_as_number */
    769     &CDataType_as_sequence,                     /* tp_as_sequence */
    770     0,                                          /* tp_as_mapping */
    771     0,                                          /* tp_hash */
    772     0,                                          /* tp_call */
    773     0,                                          /* tp_str */
    774     0,                                          /* tp_getattro */
    775     PyCStructType_setattro,                     /* tp_setattro */
    776     0,                                          /* tp_as_buffer */
    777     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
    778     "metatype for the CData Objects",           /* tp_doc */
    779     (traverseproc)CDataType_traverse,           /* tp_traverse */
    780     (inquiry)CDataType_clear,                   /* tp_clear */
    781     0,                                          /* tp_richcompare */
    782     0,                                          /* tp_weaklistoffset */
    783     0,                                          /* tp_iter */
    784     0,                                          /* tp_iternext */
    785     CDataType_methods,                          /* tp_methods */
    786     0,                                          /* tp_members */
    787     0,                                          /* tp_getset */
    788     0,                                          /* tp_base */
    789     0,                                          /* tp_dict */
    790     0,                                          /* tp_descr_get */
    791     0,                                          /* tp_descr_set */
    792     0,                                          /* tp_dictoffset */
    793     0,                                          /* tp_init */
    794     0,                                          /* tp_alloc */
    795     PyCStructType_new,                                  /* tp_new */
    796     0,                                          /* tp_free */
    797 };
    798 
    799 static PyTypeObject UnionType_Type = {
    800     PyVarObject_HEAD_INIT(NULL, 0)
    801     "_ctypes.UnionType",                        /* tp_name */
    802     0,                                          /* tp_basicsize */
    803     0,                                          /* tp_itemsize */
    804     0,                                          /* tp_dealloc */
    805     0,                                          /* tp_print */
    806     0,                                          /* tp_getattr */
    807     0,                                          /* tp_setattr */
    808     0,                                          /* tp_reserved */
    809     0,                                          /* tp_repr */
    810     0,                                          /* tp_as_number */
    811     &CDataType_as_sequence,             /* tp_as_sequence */
    812     0,                                          /* tp_as_mapping */
    813     0,                                          /* tp_hash */
    814     0,                                          /* tp_call */
    815     0,                                          /* tp_str */
    816     0,                                          /* tp_getattro */
    817     UnionType_setattro,                         /* tp_setattro */
    818     0,                                          /* tp_as_buffer */
    819     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
    820     "metatype for the CData Objects",           /* tp_doc */
    821     (traverseproc)CDataType_traverse,           /* tp_traverse */
    822     (inquiry)CDataType_clear,                   /* tp_clear */
    823     0,                                          /* tp_richcompare */
    824     0,                                          /* tp_weaklistoffset */
    825     0,                                          /* tp_iter */
    826     0,                                          /* tp_iternext */
    827     CDataType_methods,                          /* tp_methods */
    828     0,                                          /* tp_members */
    829     0,                                          /* tp_getset */
    830     0,                                          /* tp_base */
    831     0,                                          /* tp_dict */
    832     0,                                          /* tp_descr_get */
    833     0,                                          /* tp_descr_set */
    834     0,                                          /* tp_dictoffset */
    835     0,                                          /* tp_init */
    836     0,                                          /* tp_alloc */
    837     UnionType_new,                              /* tp_new */
    838     0,                                          /* tp_free */
    839 };
    840 
    841 
    842 /******************************************************************/
    843 
    844 /*
    845 
    846 The PyCPointerType_Type metaclass must ensure that the subclass of Pointer can be
    847 created. It must check for a _type_ attribute in the class. Since are no
    848 runtime created properties, a CField is probably *not* needed ?
    849 
    850 class IntPointer(Pointer):
    851     _type_ = "i"
    852 
    853 The PyCPointer_Type provides the functionality: a contents method/property, a
    854 size property/method, and the sequence protocol.
    855 
    856 */
    857 
    858 static int
    859 PyCPointerType_SetProto(StgDictObject *stgdict, PyObject *proto)
    860 {
    861     if (!proto || !PyType_Check(proto)) {
    862         PyErr_SetString(PyExc_TypeError,
    863                         "_type_ must be a type");
    864         return -1;
    865     }
    866     if (!PyType_stgdict(proto)) {
    867         PyErr_SetString(PyExc_TypeError,
    868                         "_type_ must have storage info");
    869         return -1;
    870     }
    871     Py_INCREF(proto);
    872     Py_XSETREF(stgdict->proto, proto);
    873     return 0;
    874 }
    875 
    876 static PyCArgObject *
    877 PyCPointerType_paramfunc(CDataObject *self)
    878 {
    879     PyCArgObject *parg;
    880 
    881     parg = PyCArgObject_new();
    882     if (parg == NULL)
    883         return NULL;
    884 
    885     parg->tag = 'P';
    886     parg->pffi_type = &ffi_type_pointer;
    887     Py_INCREF(self);
    888     parg->obj = (PyObject *)self;
    889     parg->value.p = *(void **)self->b_ptr;
    890     return parg;
    891 }
    892 
    893 static PyObject *
    894 PyCPointerType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    895 {
    896     PyTypeObject *result;
    897     StgDictObject *stgdict;
    898     PyObject *proto;
    899     PyObject *typedict;
    900 
    901     typedict = PyTuple_GetItem(args, 2);
    902     if (!typedict)
    903         return NULL;
    904 /*
    905   stgdict items size, align, length contain info about pointers itself,
    906   stgdict->proto has info about the pointed to type!
    907 */
    908     stgdict = (StgDictObject *)PyObject_CallObject(
    909         (PyObject *)&PyCStgDict_Type, NULL);
    910     if (!stgdict)
    911         return NULL;
    912     stgdict->size = sizeof(void *);
    913     stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment;
    914     stgdict->length = 1;
    915     stgdict->ffi_type_pointer = ffi_type_pointer;
    916     stgdict->paramfunc = PyCPointerType_paramfunc;
    917     stgdict->flags |= TYPEFLAG_ISPOINTER;
    918 
    919     proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
    920     if (proto && -1 == PyCPointerType_SetProto(stgdict, proto)) {
    921         Py_DECREF((PyObject *)stgdict);
    922         return NULL;
    923     }
    924 
    925     if (proto) {
    926         StgDictObject *itemdict = PyType_stgdict(proto);
    927         const char *current_format;
    928         assert(itemdict);
    929         /* If itemdict->format is NULL, then this is a pointer to an
    930            incomplete type.  We create a generic format string
    931            'pointer to bytes' in this case.  XXX Better would be to
    932            fix the format string later...
    933         */
    934         current_format = itemdict->format ? itemdict->format : "B";
    935         if (itemdict->shape != NULL) {
    936             /* pointer to an array: the shape needs to be prefixed */
    937             stgdict->format = _ctypes_alloc_format_string_with_shape(
    938                 itemdict->ndim, itemdict->shape, "&", current_format);
    939         } else {
    940             stgdict->format = _ctypes_alloc_format_string("&", current_format);
    941         }
    942         if (stgdict->format == NULL) {
    943             Py_DECREF((PyObject *)stgdict);
    944             return NULL;
    945         }
    946     }
    947 
    948     /* create the new instance (which is a class,
    949        since we are a metatype!) */
    950     result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
    951     if (result == NULL) {
    952         Py_DECREF((PyObject *)stgdict);
    953         return NULL;
    954     }
    955 
    956     /* replace the class dict by our updated spam dict */
    957     if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
    958         Py_DECREF(result);
    959         Py_DECREF((PyObject *)stgdict);
    960         return NULL;
    961     }
    962     Py_SETREF(result->tp_dict, (PyObject *)stgdict);
    963 
    964     return (PyObject *)result;
    965 }
    966 
    967 
    968 static PyObject *
    969 PyCPointerType_set_type(PyTypeObject *self, PyObject *type)
    970 {
    971     StgDictObject *dict;
    972 
    973     dict = PyType_stgdict((PyObject *)self);
    974     assert(dict);
    975 
    976     if (-1 == PyCPointerType_SetProto(dict, type))
    977         return NULL;
    978 
    979     if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type))
    980         return NULL;
    981 
    982     Py_INCREF(Py_None);
    983     return Py_None;
    984 }
    985 
    986 static PyObject *_byref(PyObject *);
    987 
    988 static PyObject *
    989 PyCPointerType_from_param(PyObject *type, PyObject *value)
    990 {
    991     StgDictObject *typedict;
    992 
    993     if (value == Py_None) {
    994         /* ConvParam will convert to a NULL pointer later */
    995         Py_INCREF(value);
    996         return value;
    997     }
    998 
    999     typedict = PyType_stgdict(type);
   1000     assert(typedict); /* Cannot be NULL for pointer types */
   1001 
   1002     /* If we expect POINTER(<type>), but receive a <type> instance, accept
   1003        it by calling byref(<type>).
   1004     */
   1005     switch (PyObject_IsInstance(value, typedict->proto)) {
   1006     case 1:
   1007         Py_INCREF(value); /* _byref steals a refcount */
   1008         return _byref(value);
   1009     case -1:
   1010         return NULL;
   1011     default:
   1012         break;
   1013     }
   1014 
   1015     if (PointerObject_Check(value) || ArrayObject_Check(value)) {
   1016         /* Array instances are also pointers when
   1017            the item types are the same.
   1018         */
   1019         StgDictObject *v = PyObject_stgdict(value);
   1020         assert(v); /* Cannot be NULL for pointer or array objects */
   1021         if (PyObject_IsSubclass(v->proto, typedict->proto)) {
   1022             Py_INCREF(value);
   1023             return value;
   1024         }
   1025     }
   1026     return CDataType_from_param(type, value);
   1027 }
   1028 
   1029 static PyMethodDef PyCPointerType_methods[] = {
   1030     { "from_address", CDataType_from_address, METH_O, from_address_doc },
   1031     { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
   1032     { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
   1033     { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
   1034     { "from_param", (PyCFunction)PyCPointerType_from_param, METH_O, from_param_doc},
   1035     { "set_type", (PyCFunction)PyCPointerType_set_type, METH_O },
   1036     { NULL, NULL },
   1037 };
   1038 
   1039 PyTypeObject PyCPointerType_Type = {
   1040     PyVarObject_HEAD_INIT(NULL, 0)
   1041     "_ctypes.PyCPointerType",                                   /* tp_name */
   1042     0,                                          /* tp_basicsize */
   1043     0,                                          /* tp_itemsize */
   1044     0,                                          /* tp_dealloc */
   1045     0,                                          /* tp_print */
   1046     0,                                          /* tp_getattr */
   1047     0,                                          /* tp_setattr */
   1048     0,                                          /* tp_reserved */
   1049     0,                                          /* tp_repr */
   1050     0,                                          /* tp_as_number */
   1051     &CDataType_as_sequence,             /* tp_as_sequence */
   1052     0,                                          /* tp_as_mapping */
   1053     0,                                          /* tp_hash */
   1054     0,                                          /* tp_call */
   1055     0,                                          /* tp_str */
   1056     0,                                          /* tp_getattro */
   1057     0,                                          /* tp_setattro */
   1058     0,                                          /* tp_as_buffer */
   1059     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
   1060     "metatype for the Pointer Objects",         /* tp_doc */
   1061     (traverseproc)CDataType_traverse,           /* tp_traverse */
   1062     (inquiry)CDataType_clear,                   /* tp_clear */
   1063     0,                                          /* tp_richcompare */
   1064     0,                                          /* tp_weaklistoffset */
   1065     0,                                          /* tp_iter */
   1066     0,                                          /* tp_iternext */
   1067     PyCPointerType_methods,                     /* tp_methods */
   1068     0,                                          /* tp_members */
   1069     0,                                          /* tp_getset */
   1070     0,                                          /* tp_base */
   1071     0,                                          /* tp_dict */
   1072     0,                                          /* tp_descr_get */
   1073     0,                                          /* tp_descr_set */
   1074     0,                                          /* tp_dictoffset */
   1075     0,                                          /* tp_init */
   1076     0,                                          /* tp_alloc */
   1077     PyCPointerType_new,                         /* tp_new */
   1078     0,                                          /* tp_free */
   1079 };
   1080 
   1081 
   1082 /******************************************************************/
   1083 /*
   1084   PyCArrayType_Type
   1085 */
   1086 /*
   1087   PyCArrayType_new ensures that the new Array subclass created has a _length_
   1088   attribute, and a _type_ attribute.
   1089 */
   1090 
   1091 static int
   1092 CharArray_set_raw(CDataObject *self, PyObject *value)
   1093 {
   1094     char *ptr;
   1095     Py_ssize_t size;
   1096     Py_buffer view;
   1097 
   1098     if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0)
   1099         return -1;
   1100     size = view.len;
   1101     ptr = view.buf;
   1102     if (size > self->b_size) {
   1103         PyErr_SetString(PyExc_ValueError,
   1104                         "byte string too long");
   1105         goto fail;
   1106     }
   1107 
   1108     memcpy(self->b_ptr, ptr, size);
   1109 
   1110     PyBuffer_Release(&view);
   1111     return 0;
   1112  fail:
   1113     PyBuffer_Release(&view);
   1114     return -1;
   1115 }
   1116 
   1117 static PyObject *
   1118 CharArray_get_raw(CDataObject *self)
   1119 {
   1120     return PyBytes_FromStringAndSize(self->b_ptr, self->b_size);
   1121 }
   1122 
   1123 static PyObject *
   1124 CharArray_get_value(CDataObject *self)
   1125 {
   1126     Py_ssize_t i;
   1127     char *ptr = self->b_ptr;
   1128     for (i = 0; i < self->b_size; ++i)
   1129         if (*ptr++ == '\0')
   1130             break;
   1131     return PyBytes_FromStringAndSize(self->b_ptr, i);
   1132 }
   1133 
   1134 static int
   1135 CharArray_set_value(CDataObject *self, PyObject *value)
   1136 {
   1137     char *ptr;
   1138     Py_ssize_t size;
   1139 
   1140     if (value == NULL) {
   1141         PyErr_SetString(PyExc_TypeError,
   1142                         "can't delete attribute");
   1143         return -1;
   1144     }
   1145 
   1146     if (!PyBytes_Check(value)) {
   1147         PyErr_Format(PyExc_TypeError,
   1148                      "bytes expected instead of %s instance",
   1149                      Py_TYPE(value)->tp_name);
   1150         return -1;
   1151     } else
   1152         Py_INCREF(value);
   1153     size = PyBytes_GET_SIZE(value);
   1154     if (size > self->b_size) {
   1155         PyErr_SetString(PyExc_ValueError,
   1156                         "byte string too long");
   1157         Py_DECREF(value);
   1158         return -1;
   1159     }
   1160 
   1161     ptr = PyBytes_AS_STRING(value);
   1162     memcpy(self->b_ptr, ptr, size);
   1163     if (size < self->b_size)
   1164         self->b_ptr[size] = '\0';
   1165     Py_DECREF(value);
   1166 
   1167     return 0;
   1168 }
   1169 
   1170 static PyGetSetDef CharArray_getsets[] = {
   1171     { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw,
   1172       "value", NULL },
   1173     { "value", (getter)CharArray_get_value, (setter)CharArray_set_value,
   1174       "string value"},
   1175     { NULL, NULL }
   1176 };
   1177 
   1178 #ifdef CTYPES_UNICODE
   1179 static PyObject *
   1180 WCharArray_get_value(CDataObject *self)
   1181 {
   1182     Py_ssize_t i;
   1183     wchar_t *ptr = (wchar_t *)self->b_ptr;
   1184     for (i = 0; i < self->b_size/(Py_ssize_t)sizeof(wchar_t); ++i)
   1185         if (*ptr++ == (wchar_t)0)
   1186             break;
   1187     return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i);
   1188 }
   1189 
   1190 static int
   1191 WCharArray_set_value(CDataObject *self, PyObject *value)
   1192 {
   1193     Py_ssize_t result = 0;
   1194     Py_UNICODE *wstr;
   1195     Py_ssize_t len;
   1196 
   1197     if (value == NULL) {
   1198         PyErr_SetString(PyExc_TypeError,
   1199                         "can't delete attribute");
   1200         return -1;
   1201     }
   1202     if (!PyUnicode_Check(value)) {
   1203         PyErr_Format(PyExc_TypeError,
   1204                         "unicode string expected instead of %s instance",
   1205                         Py_TYPE(value)->tp_name);
   1206         return -1;
   1207     } else
   1208         Py_INCREF(value);
   1209 
   1210     wstr = PyUnicode_AsUnicodeAndSize(value, &len);
   1211     if (wstr == NULL)
   1212         return -1;
   1213     if ((size_t)len > self->b_size/sizeof(wchar_t)) {
   1214         PyErr_SetString(PyExc_ValueError,
   1215                         "string too long");
   1216         result = -1;
   1217         goto done;
   1218     }
   1219     result = PyUnicode_AsWideChar(value,
   1220                                   (wchar_t *)self->b_ptr,
   1221                                   self->b_size/sizeof(wchar_t));
   1222     if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t))
   1223         ((wchar_t *)self->b_ptr)[result] = (wchar_t)0;
   1224   done:
   1225     Py_DECREF(value);
   1226 
   1227     return result >= 0 ? 0 : -1;
   1228 }
   1229 
   1230 static PyGetSetDef WCharArray_getsets[] = {
   1231     { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value,
   1232       "string value"},
   1233     { NULL, NULL }
   1234 };
   1235 #endif
   1236 
   1237 /*
   1238   The next three functions copied from Python's typeobject.c.
   1239 
   1240   They are used to attach methods, members, or getsets to a type *after* it
   1241   has been created: Arrays of characters have additional getsets to treat them
   1242   as strings.
   1243  */
   1244 /*
   1245 static int
   1246 add_methods(PyTypeObject *type, PyMethodDef *meth)
   1247 {
   1248     PyObject *dict = type->tp_dict;
   1249     for (; meth->ml_name != NULL; meth++) {
   1250         PyObject *descr;
   1251         descr = PyDescr_NewMethod(type, meth);
   1252         if (descr == NULL)
   1253             return -1;
   1254         if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0) {
   1255             Py_DECREF(descr);
   1256             return -1;
   1257         }
   1258         Py_DECREF(descr);
   1259     }
   1260     return 0;
   1261 }
   1262 
   1263 static int
   1264 add_members(PyTypeObject *type, PyMemberDef *memb)
   1265 {
   1266     PyObject *dict = type->tp_dict;
   1267     for (; memb->name != NULL; memb++) {
   1268         PyObject *descr;
   1269         descr = PyDescr_NewMember(type, memb);
   1270         if (descr == NULL)
   1271             return -1;
   1272         if (PyDict_SetItemString(dict, memb->name, descr) < 0) {
   1273             Py_DECREF(descr);
   1274             return -1;
   1275         }
   1276         Py_DECREF(descr);
   1277     }
   1278     return 0;
   1279 }
   1280 */
   1281 
   1282 static int
   1283 add_getset(PyTypeObject *type, PyGetSetDef *gsp)
   1284 {
   1285     PyObject *dict = type->tp_dict;
   1286     for (; gsp->name != NULL; gsp++) {
   1287         PyObject *descr;
   1288         descr = PyDescr_NewGetSet(type, gsp);
   1289         if (descr == NULL)
   1290             return -1;
   1291         if (PyDict_SetItemString(dict, gsp->name, descr) < 0) {
   1292             Py_DECREF(descr);
   1293             return -1;
   1294         }
   1295         Py_DECREF(descr);
   1296     }
   1297     return 0;
   1298 }
   1299 
   1300 static PyCArgObject *
   1301 PyCArrayType_paramfunc(CDataObject *self)
   1302 {
   1303     PyCArgObject *p = PyCArgObject_new();
   1304     if (p == NULL)
   1305         return NULL;
   1306     p->tag = 'P';
   1307     p->pffi_type = &ffi_type_pointer;
   1308     p->value.p = (char *)self->b_ptr;
   1309     Py_INCREF(self);
   1310     p->obj = (PyObject *)self;
   1311     return p;
   1312 }
   1313 
   1314 static PyObject *
   1315 PyCArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
   1316 {
   1317     PyTypeObject *result;
   1318     StgDictObject *stgdict;
   1319     StgDictObject *itemdict;
   1320     PyObject *length_attr, *type_attr;
   1321     long length;
   1322     int overflow;
   1323     Py_ssize_t itemsize, itemalign;
   1324 
   1325     /* create the new instance (which is a class,
   1326        since we are a metatype!) */
   1327     result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
   1328     if (result == NULL)
   1329         return NULL;
   1330 
   1331     /* Initialize these variables to NULL so that we can simplify error
   1332        handling by using Py_XDECREF.  */
   1333     stgdict = NULL;
   1334     type_attr = NULL;
   1335 
   1336     length_attr = PyObject_GetAttrString((PyObject *)result, "_length_");
   1337     if (!length_attr || !PyLong_Check(length_attr)) {
   1338         PyErr_SetString(PyExc_AttributeError,
   1339                         "class must define a '_length_' attribute, "
   1340                         "which must be a positive integer");
   1341         Py_XDECREF(length_attr);
   1342         goto error;
   1343     }
   1344     length = PyLong_AsLongAndOverflow(length_attr, &overflow);
   1345     if (overflow) {
   1346         PyErr_SetString(PyExc_OverflowError,
   1347                         "The '_length_' attribute is too large");
   1348         Py_DECREF(length_attr);
   1349         goto error;
   1350     }
   1351     Py_DECREF(length_attr);
   1352 
   1353     type_attr = PyObject_GetAttrString((PyObject *)result, "_type_");
   1354     if (!type_attr) {
   1355         PyErr_SetString(PyExc_AttributeError,
   1356                         "class must define a '_type_' attribute");
   1357         goto error;
   1358     }
   1359 
   1360     stgdict = (StgDictObject *)PyObject_CallObject(
   1361         (PyObject *)&PyCStgDict_Type, NULL);
   1362     if (!stgdict)
   1363         goto error;
   1364 
   1365     itemdict = PyType_stgdict(type_attr);
   1366     if (!itemdict) {
   1367         PyErr_SetString(PyExc_TypeError,
   1368                         "_type_ must have storage info");
   1369         goto error;
   1370     }
   1371 
   1372     assert(itemdict->format);
   1373     stgdict->format = _ctypes_alloc_format_string(NULL, itemdict->format);
   1374     if (stgdict->format == NULL)
   1375         goto error;
   1376     stgdict->ndim = itemdict->ndim + 1;
   1377     stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t) * stgdict->ndim);
   1378     if (stgdict->shape == NULL) {
   1379         PyErr_NoMemory();
   1380         goto error;
   1381     }
   1382     stgdict->shape[0] = length;
   1383     if (stgdict->ndim > 1) {
   1384         memmove(&stgdict->shape[1], itemdict->shape,
   1385             sizeof(Py_ssize_t) * (stgdict->ndim - 1));
   1386     }
   1387 
   1388     itemsize = itemdict->size;
   1389     if (length * itemsize < 0) {
   1390         PyErr_SetString(PyExc_OverflowError,
   1391                         "array too large");
   1392         goto error;
   1393     }
   1394 
   1395     itemalign = itemdict->align;
   1396 
   1397     if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
   1398         stgdict->flags |= TYPEFLAG_HASPOINTER;
   1399 
   1400     stgdict->size = itemsize * length;
   1401     stgdict->align = itemalign;
   1402     stgdict->length = length;
   1403     stgdict->proto = type_attr;
   1404 
   1405     stgdict->paramfunc = &PyCArrayType_paramfunc;
   1406 
   1407     /* Arrays are passed as pointers to function calls. */
   1408     stgdict->ffi_type_pointer = ffi_type_pointer;
   1409 
   1410     /* replace the class dict by our updated spam dict */
   1411     if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict))
   1412         goto error;
   1413     Py_SETREF(result->tp_dict, (PyObject *)stgdict);  /* steal the reference */
   1414     stgdict = NULL;
   1415 
   1416     /* Special case for character arrays.
   1417        A permanent annoyance: char arrays are also strings!
   1418     */
   1419     if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
   1420         if (-1 == add_getset(result, CharArray_getsets))
   1421             goto error;
   1422 #ifdef CTYPES_UNICODE
   1423     } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
   1424         if (-1 == add_getset(result, WCharArray_getsets))
   1425             goto error;
   1426 #endif
   1427     }
   1428 
   1429     return (PyObject *)result;
   1430 error:
   1431     Py_XDECREF((PyObject*)stgdict);
   1432     Py_XDECREF(type_attr);
   1433     Py_DECREF(result);
   1434     return NULL;
   1435 }
   1436 
   1437 PyTypeObject PyCArrayType_Type = {
   1438     PyVarObject_HEAD_INIT(NULL, 0)
   1439     "_ctypes.PyCArrayType",                     /* tp_name */
   1440     0,                                          /* tp_basicsize */
   1441     0,                                          /* tp_itemsize */
   1442     0,                                          /* tp_dealloc */
   1443     0,                                          /* tp_print */
   1444     0,                                          /* tp_getattr */
   1445     0,                                          /* tp_setattr */
   1446     0,                                          /* tp_reserved */
   1447     0,                                          /* tp_repr */
   1448     0,                                          /* tp_as_number */
   1449     &CDataType_as_sequence,                     /* tp_as_sequence */
   1450     0,                                          /* tp_as_mapping */
   1451     0,                                          /* tp_hash */
   1452     0,                                          /* tp_call */
   1453     0,                                          /* tp_str */
   1454     0,                                          /* tp_getattro */
   1455     0,                                          /* tp_setattro */
   1456     0,                                          /* tp_as_buffer */
   1457     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
   1458     "metatype for the Array Objects",           /* tp_doc */
   1459     0,                                          /* tp_traverse */
   1460     0,                                          /* tp_clear */
   1461     0,                                          /* tp_richcompare */
   1462     0,                                          /* tp_weaklistoffset */
   1463     0,                                          /* tp_iter */
   1464     0,                                          /* tp_iternext */
   1465     CDataType_methods,                          /* tp_methods */
   1466     0,                                          /* tp_members */
   1467     0,                                          /* tp_getset */
   1468     0,                                          /* tp_base */
   1469     0,                                          /* tp_dict */
   1470     0,                                          /* tp_descr_get */
   1471     0,                                          /* tp_descr_set */
   1472     0,                                          /* tp_dictoffset */
   1473     0,                                          /* tp_init */
   1474     0,                                          /* tp_alloc */
   1475     PyCArrayType_new,                                   /* tp_new */
   1476     0,                                          /* tp_free */
   1477 };
   1478 
   1479 
   1480 /******************************************************************/
   1481 /*
   1482   PyCSimpleType_Type
   1483 */
   1484 /*
   1485 
   1486 PyCSimpleType_new ensures that the new Simple_Type subclass created has a valid
   1487 _type_ attribute.
   1488 
   1489 */
   1490 
   1491 static const char SIMPLE_TYPE_CHARS[] = "cbBhHiIlLdfuzZqQPXOv?g";
   1492 
   1493 static PyObject *
   1494 c_wchar_p_from_param(PyObject *type, PyObject *value)
   1495 {
   1496     PyObject *as_parameter;
   1497     int res;
   1498     if (value == Py_None) {
   1499         Py_INCREF(Py_None);
   1500         return Py_None;
   1501     }
   1502     if (PyUnicode_Check(value)) {
   1503         PyCArgObject *parg;
   1504         struct fielddesc *fd = _ctypes_get_fielddesc("Z");
   1505 
   1506         parg = PyCArgObject_new();
   1507         if (parg == NULL)
   1508             return NULL;
   1509         parg->pffi_type = &ffi_type_pointer;
   1510         parg->tag = 'Z';
   1511         parg->obj = fd->setfunc(&parg->value, value, 0);
   1512         if (parg->obj == NULL) {
   1513             Py_DECREF(parg);
   1514             return NULL;
   1515         }
   1516         return (PyObject *)parg;
   1517     }
   1518     res = PyObject_IsInstance(value, type);
   1519     if (res == -1)
   1520         return NULL;
   1521     if (res) {
   1522         Py_INCREF(value);
   1523         return value;
   1524     }
   1525     if (ArrayObject_Check(value) || PointerObject_Check(value)) {
   1526         /* c_wchar array instance or pointer(c_wchar(...)) */
   1527         StgDictObject *dt = PyObject_stgdict(value);
   1528         StgDictObject *dict;
   1529         assert(dt); /* Cannot be NULL for pointer or array objects */
   1530         dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
   1531         if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) {
   1532             Py_INCREF(value);
   1533             return value;
   1534         }
   1535     }
   1536     if (PyCArg_CheckExact(value)) {
   1537         /* byref(c_char(...)) */
   1538         PyCArgObject *a = (PyCArgObject *)value;
   1539         StgDictObject *dict = PyObject_stgdict(a->obj);
   1540         if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) {
   1541             Py_INCREF(value);
   1542             return value;
   1543         }
   1544     }
   1545 
   1546     as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
   1547     if (as_parameter) {
   1548         value = c_wchar_p_from_param(type, as_parameter);
   1549         Py_DECREF(as_parameter);
   1550         return value;
   1551     }
   1552     /* XXX better message */
   1553     PyErr_SetString(PyExc_TypeError,
   1554                     "wrong type");
   1555     return NULL;
   1556 }
   1557 
   1558 static PyObject *
   1559 c_char_p_from_param(PyObject *type, PyObject *value)
   1560 {
   1561     PyObject *as_parameter;
   1562     int res;
   1563     if (value == Py_None) {
   1564         Py_INCREF(Py_None);
   1565         return Py_None;
   1566     }
   1567     if (PyBytes_Check(value)) {
   1568         PyCArgObject *parg;
   1569         struct fielddesc *fd = _ctypes_get_fielddesc("z");
   1570 
   1571         parg = PyCArgObject_new();
   1572         if (parg == NULL)
   1573             return NULL;
   1574         parg->pffi_type = &ffi_type_pointer;
   1575         parg->tag = 'z';
   1576         parg->obj = fd->setfunc(&parg->value, value, 0);
   1577         if (parg->obj == NULL) {
   1578             Py_DECREF(parg);
   1579             return NULL;
   1580         }
   1581         return (PyObject *)parg;
   1582     }
   1583     res = PyObject_IsInstance(value, type);
   1584     if (res == -1)
   1585         return NULL;
   1586     if (res) {
   1587         Py_INCREF(value);
   1588         return value;
   1589     }
   1590     if (ArrayObject_Check(value) || PointerObject_Check(value)) {
   1591         /* c_char array instance or pointer(c_char(...)) */
   1592         StgDictObject *dt = PyObject_stgdict(value);
   1593         StgDictObject *dict;
   1594         assert(dt); /* Cannot be NULL for pointer or array objects */
   1595         dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
   1596         if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) {
   1597             Py_INCREF(value);
   1598             return value;
   1599         }
   1600     }
   1601     if (PyCArg_CheckExact(value)) {
   1602         /* byref(c_char(...)) */
   1603         PyCArgObject *a = (PyCArgObject *)value;
   1604         StgDictObject *dict = PyObject_stgdict(a->obj);
   1605         if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) {
   1606             Py_INCREF(value);
   1607             return value;
   1608         }
   1609     }
   1610 
   1611     as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
   1612     if (as_parameter) {
   1613         value = c_char_p_from_param(type, as_parameter);
   1614         Py_DECREF(as_parameter);
   1615         return value;
   1616     }
   1617     /* XXX better message */
   1618     PyErr_SetString(PyExc_TypeError,
   1619                     "wrong type");
   1620     return NULL;
   1621 }
   1622 
   1623 static PyObject *
   1624 c_void_p_from_param(PyObject *type, PyObject *value)
   1625 {
   1626     StgDictObject *stgd;
   1627     PyObject *as_parameter;
   1628     int res;
   1629 
   1630 /* None */
   1631     if (value == Py_None) {
   1632         Py_INCREF(Py_None);
   1633         return Py_None;
   1634     }
   1635     /* Should probably allow buffer interface as well */
   1636 /* int, long */
   1637     if (PyLong_Check(value)) {
   1638         PyCArgObject *parg;
   1639         struct fielddesc *fd = _ctypes_get_fielddesc("P");
   1640 
   1641         parg = PyCArgObject_new();
   1642         if (parg == NULL)
   1643             return NULL;
   1644         parg->pffi_type = &ffi_type_pointer;
   1645         parg->tag = 'P';
   1646         parg->obj = fd->setfunc(&parg->value, value, 0);
   1647         if (parg->obj == NULL) {
   1648             Py_DECREF(parg);
   1649             return NULL;
   1650         }
   1651         return (PyObject *)parg;
   1652     }
   1653     /* XXX struni: remove later */
   1654 /* bytes */
   1655     if (PyBytes_Check(value)) {
   1656         PyCArgObject *parg;
   1657         struct fielddesc *fd = _ctypes_get_fielddesc("z");
   1658 
   1659         parg = PyCArgObject_new();
   1660         if (parg == NULL)
   1661             return NULL;
   1662         parg->pffi_type = &ffi_type_pointer;
   1663         parg->tag = 'z';
   1664         parg->obj = fd->setfunc(&parg->value, value, 0);
   1665         if (parg->obj == NULL) {
   1666             Py_DECREF(parg);
   1667             return NULL;
   1668         }
   1669         return (PyObject *)parg;
   1670     }
   1671 /* unicode */
   1672     if (PyUnicode_Check(value)) {
   1673         PyCArgObject *parg;
   1674         struct fielddesc *fd = _ctypes_get_fielddesc("Z");
   1675 
   1676         parg = PyCArgObject_new();
   1677         if (parg == NULL)
   1678             return NULL;
   1679         parg->pffi_type = &ffi_type_pointer;
   1680         parg->tag = 'Z';
   1681         parg->obj = fd->setfunc(&parg->value, value, 0);
   1682         if (parg->obj == NULL) {
   1683             Py_DECREF(parg);
   1684             return NULL;
   1685         }
   1686         return (PyObject *)parg;
   1687     }
   1688 /* c_void_p instance (or subclass) */
   1689     res = PyObject_IsInstance(value, type);
   1690     if (res == -1)
   1691         return NULL;
   1692     if (res) {
   1693         /* c_void_p instances */
   1694         Py_INCREF(value);
   1695         return value;
   1696     }
   1697 /* ctypes array or pointer instance */
   1698     if (ArrayObject_Check(value) || PointerObject_Check(value)) {
   1699         /* Any array or pointer is accepted */
   1700         Py_INCREF(value);
   1701         return value;
   1702     }
   1703 /* byref(...) */
   1704     if (PyCArg_CheckExact(value)) {
   1705         /* byref(c_xxx()) */
   1706         PyCArgObject *a = (PyCArgObject *)value;
   1707         if (a->tag == 'P') {
   1708             Py_INCREF(value);
   1709             return value;
   1710         }
   1711     }
   1712 /* function pointer */
   1713     if (PyCFuncPtrObject_Check(value)) {
   1714         PyCArgObject *parg;
   1715         PyCFuncPtrObject *func;
   1716         func = (PyCFuncPtrObject *)value;
   1717         parg = PyCArgObject_new();
   1718         if (parg == NULL)
   1719             return NULL;
   1720         parg->pffi_type = &ffi_type_pointer;
   1721         parg->tag = 'P';
   1722         Py_INCREF(value);
   1723         parg->value.p = *(void **)func->b_ptr;
   1724         parg->obj = value;
   1725         return (PyObject *)parg;
   1726     }
   1727 /* c_char_p, c_wchar_p */
   1728     stgd = PyObject_stgdict(value);
   1729     if (stgd && CDataObject_Check(value) && stgd->proto && PyUnicode_Check(stgd->proto)) {
   1730         PyCArgObject *parg;
   1731 
   1732         switch (PyUnicode_AsUTF8(stgd->proto)[0]) {
   1733         case 'z': /* c_char_p */
   1734         case 'Z': /* c_wchar_p */
   1735             parg = PyCArgObject_new();
   1736             if (parg == NULL)
   1737                 return NULL;
   1738             parg->pffi_type = &ffi_type_pointer;
   1739             parg->tag = 'Z';
   1740             Py_INCREF(value);
   1741             parg->obj = value;
   1742             /* Remember: b_ptr points to where the pointer is stored! */
   1743             parg->value.p = *(void **)(((CDataObject *)value)->b_ptr);
   1744             return (PyObject *)parg;
   1745         }
   1746     }
   1747 
   1748     as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
   1749     if (as_parameter) {
   1750         value = c_void_p_from_param(type, as_parameter);
   1751         Py_DECREF(as_parameter);
   1752         return value;
   1753     }
   1754     /* XXX better message */
   1755     PyErr_SetString(PyExc_TypeError,
   1756                     "wrong type");
   1757     return NULL;
   1758 }
   1759 
   1760 static PyMethodDef c_void_p_method = { "from_param", c_void_p_from_param, METH_O };
   1761 static PyMethodDef c_char_p_method = { "from_param", c_char_p_from_param, METH_O };
   1762 static PyMethodDef c_wchar_p_method = { "from_param", c_wchar_p_from_param, METH_O };
   1763 
   1764 static PyObject *CreateSwappedType(PyTypeObject *type, PyObject *args, PyObject *kwds,
   1765                                    PyObject *proto, struct fielddesc *fmt)
   1766 {
   1767     PyTypeObject *result;
   1768     StgDictObject *stgdict;
   1769     PyObject *name = PyTuple_GET_ITEM(args, 0);
   1770     PyObject *newname;
   1771     PyObject *swapped_args;
   1772     static PyObject *suffix;
   1773     Py_ssize_t i;
   1774 
   1775     swapped_args = PyTuple_New(PyTuple_GET_SIZE(args));
   1776     if (!swapped_args)
   1777         return NULL;
   1778 
   1779     if (suffix == NULL)
   1780 #ifdef WORDS_BIGENDIAN
   1781         suffix = PyUnicode_InternFromString("_le");
   1782 #else
   1783         suffix = PyUnicode_InternFromString("_be");
   1784 #endif
   1785 
   1786     newname = PyUnicode_Concat(name, suffix);
   1787     if (newname == NULL) {
   1788         Py_DECREF(swapped_args);
   1789         return NULL;
   1790     }
   1791 
   1792     PyTuple_SET_ITEM(swapped_args, 0, newname);
   1793     for (i=1; i<PyTuple_GET_SIZE(args); ++i) {
   1794         PyObject *v = PyTuple_GET_ITEM(args, i);
   1795         Py_INCREF(v);
   1796         PyTuple_SET_ITEM(swapped_args, i, v);
   1797     }
   1798 
   1799     /* create the new instance (which is a class,
   1800        since we are a metatype!) */
   1801     result = (PyTypeObject *)PyType_Type.tp_new(type, swapped_args, kwds);
   1802     Py_DECREF(swapped_args);
   1803     if (result == NULL)
   1804         return NULL;
   1805 
   1806     stgdict = (StgDictObject *)PyObject_CallObject(
   1807         (PyObject *)&PyCStgDict_Type, NULL);
   1808     if (!stgdict) {
   1809         Py_DECREF(result);
   1810         return NULL;
   1811     }
   1812 
   1813     stgdict->ffi_type_pointer = *fmt->pffi_type;
   1814     stgdict->align = fmt->pffi_type->alignment;
   1815     stgdict->length = 0;
   1816     stgdict->size = fmt->pffi_type->size;
   1817     stgdict->setfunc = fmt->setfunc_swapped;
   1818     stgdict->getfunc = fmt->getfunc_swapped;
   1819 
   1820     Py_INCREF(proto);
   1821     stgdict->proto = proto;
   1822 
   1823     /* replace the class dict by our updated spam dict */
   1824     if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
   1825         Py_DECREF(result);
   1826         Py_DECREF((PyObject *)stgdict);
   1827         return NULL;
   1828     }
   1829     Py_SETREF(result->tp_dict, (PyObject *)stgdict);
   1830 
   1831     return (PyObject *)result;
   1832 }
   1833 
   1834 static PyCArgObject *
   1835 PyCSimpleType_paramfunc(CDataObject *self)
   1836 {
   1837     StgDictObject *dict;
   1838     char *fmt;
   1839     PyCArgObject *parg;
   1840     struct fielddesc *fd;
   1841 
   1842     dict = PyObject_stgdict((PyObject *)self);
   1843     assert(dict); /* Cannot be NULL for CDataObject instances */
   1844     fmt = PyUnicode_AsUTF8(dict->proto);
   1845     assert(fmt);
   1846 
   1847     fd = _ctypes_get_fielddesc(fmt);
   1848     assert(fd);
   1849 
   1850     parg = PyCArgObject_new();
   1851     if (parg == NULL)
   1852         return NULL;
   1853 
   1854     parg->tag = fmt[0];
   1855     parg->pffi_type = fd->pffi_type;
   1856     Py_INCREF(self);
   1857     parg->obj = (PyObject *)self;
   1858     memcpy(&parg->value, self->b_ptr, self->b_size);
   1859     return parg;
   1860 }
   1861 
   1862 static PyObject *
   1863 PyCSimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
   1864 {
   1865     PyTypeObject *result;
   1866     StgDictObject *stgdict;
   1867     PyObject *proto;
   1868     const char *proto_str;
   1869     Py_ssize_t proto_len;
   1870     PyMethodDef *ml;
   1871     struct fielddesc *fmt;
   1872 
   1873     /* create the new instance (which is a class,
   1874        since we are a metatype!) */
   1875     result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
   1876     if (result == NULL)
   1877         return NULL;
   1878 
   1879     proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */
   1880     if (!proto) {
   1881         PyErr_SetString(PyExc_AttributeError,
   1882                         "class must define a '_type_' attribute");
   1883   error:
   1884         Py_XDECREF(proto);
   1885         Py_XDECREF(result);
   1886         return NULL;
   1887     }
   1888     if (PyUnicode_Check(proto)) {
   1889         proto_str = PyUnicode_AsUTF8AndSize(proto, &proto_len);
   1890         if (!proto_str)
   1891             goto error;
   1892     } else {
   1893         PyErr_SetString(PyExc_TypeError,
   1894             "class must define a '_type_' string attribute");
   1895         goto error;
   1896     }
   1897     if (proto_len != 1) {
   1898         PyErr_SetString(PyExc_ValueError,
   1899                         "class must define a '_type_' attribute "
   1900                         "which must be a string of length 1");
   1901         goto error;
   1902     }
   1903     if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) {
   1904         PyErr_Format(PyExc_AttributeError,
   1905                      "class must define a '_type_' attribute which must be\n"
   1906                      "a single character string containing one of '%s'.",
   1907                      SIMPLE_TYPE_CHARS);
   1908         goto error;
   1909     }
   1910     fmt = _ctypes_get_fielddesc(proto_str);
   1911     if (fmt == NULL) {
   1912         PyErr_Format(PyExc_ValueError,
   1913                      "_type_ '%s' not supported", proto_str);
   1914         goto error;
   1915     }
   1916 
   1917     stgdict = (StgDictObject *)PyObject_CallObject(
   1918         (PyObject *)&PyCStgDict_Type, NULL);
   1919     if (!stgdict)
   1920         goto error;
   1921 
   1922     stgdict->ffi_type_pointer = *fmt->pffi_type;
   1923     stgdict->align = fmt->pffi_type->alignment;
   1924     stgdict->length = 0;
   1925     stgdict->size = fmt->pffi_type->size;
   1926     stgdict->setfunc = fmt->setfunc;
   1927     stgdict->getfunc = fmt->getfunc;
   1928 #ifdef WORDS_BIGENDIAN
   1929     stgdict->format = _ctypes_alloc_format_string(">", proto_str);
   1930 #else
   1931     stgdict->format = _ctypes_alloc_format_string("<", proto_str);
   1932 #endif
   1933     if (stgdict->format == NULL) {
   1934         Py_DECREF(result);
   1935         Py_DECREF(proto);
   1936         Py_DECREF((PyObject *)stgdict);
   1937         return NULL;
   1938     }
   1939 
   1940     stgdict->paramfunc = PyCSimpleType_paramfunc;
   1941 /*
   1942     if (result->tp_base != &Simple_Type) {
   1943         stgdict->setfunc = NULL;
   1944         stgdict->getfunc = NULL;
   1945     }
   1946 */
   1947 
   1948     /* This consumes the refcount on proto which we have */
   1949     stgdict->proto = proto;
   1950 
   1951     /* replace the class dict by our updated spam dict */
   1952     if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
   1953         Py_DECREF(result);
   1954         Py_DECREF((PyObject *)stgdict);
   1955         return NULL;
   1956     }
   1957     Py_SETREF(result->tp_dict, (PyObject *)stgdict);
   1958 
   1959     /* Install from_param class methods in ctypes base classes.
   1960        Overrides the PyCSimpleType_from_param generic method.
   1961      */
   1962     if (result->tp_base == &Simple_Type) {
   1963         switch (*proto_str) {
   1964         case 'z': /* c_char_p */
   1965             ml = &c_char_p_method;
   1966             stgdict->flags |= TYPEFLAG_ISPOINTER;
   1967             break;
   1968         case 'Z': /* c_wchar_p */
   1969             ml = &c_wchar_p_method;
   1970             stgdict->flags |= TYPEFLAG_ISPOINTER;
   1971             break;
   1972         case 'P': /* c_void_p */
   1973             ml = &c_void_p_method;
   1974             stgdict->flags |= TYPEFLAG_ISPOINTER;
   1975             break;
   1976         case 's':
   1977         case 'X':
   1978         case 'O':
   1979             ml = NULL;
   1980             stgdict->flags |= TYPEFLAG_ISPOINTER;
   1981             break;
   1982         default:
   1983             ml = NULL;
   1984             break;
   1985         }
   1986 
   1987         if (ml) {
   1988             PyObject *meth;
   1989             int x;
   1990             meth = PyDescr_NewClassMethod(result, ml);
   1991             if (!meth) {
   1992                 Py_DECREF(result);
   1993                 return NULL;
   1994             }
   1995             x = PyDict_SetItemString(result->tp_dict,
   1996                                      ml->ml_name,
   1997                                      meth);
   1998             Py_DECREF(meth);
   1999             if (x == -1) {
   2000                 Py_DECREF(result);
   2001                 return NULL;
   2002             }
   2003         }
   2004     }
   2005 
   2006     if (type == &PyCSimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) {
   2007         PyObject *swapped = CreateSwappedType(type, args, kwds,
   2008                                               proto, fmt);
   2009         StgDictObject *sw_dict;
   2010         if (swapped == NULL) {
   2011             Py_DECREF(result);
   2012             return NULL;
   2013         }
   2014         sw_dict = PyType_stgdict(swapped);
   2015 #ifdef WORDS_BIGENDIAN
   2016         PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped);
   2017         PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result);
   2018         PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result);
   2019         PyObject_SetAttrString(swapped, "__ctype_le__", swapped);
   2020         /* We are creating the type for the OTHER endian */
   2021         sw_dict->format = _ctypes_alloc_format_string("<", stgdict->format+1);
   2022 #else
   2023         PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped);
   2024         PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result);
   2025         PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result);
   2026         PyObject_SetAttrString(swapped, "__ctype_be__", swapped);
   2027         /* We are creating the type for the OTHER endian */
   2028         sw_dict->format = _ctypes_alloc_format_string(">", stgdict->format+1);
   2029 #endif
   2030         Py_DECREF(swapped);
   2031         if (PyErr_Occurred()) {
   2032             Py_DECREF(result);
   2033             return NULL;
   2034         }
   2035     };
   2036 
   2037     return (PyObject *)result;
   2038 }
   2039 
   2040 /*
   2041  * This is a *class method*.
   2042  * Convert a parameter into something that ConvParam can handle.
   2043  */
   2044 static PyObject *
   2045 PyCSimpleType_from_param(PyObject *type, PyObject *value)
   2046 {
   2047     StgDictObject *dict;
   2048     char *fmt;
   2049     PyCArgObject *parg;
   2050     struct fielddesc *fd;
   2051     PyObject *as_parameter;
   2052     int res;
   2053 
   2054     /* If the value is already an instance of the requested type,
   2055        we can use it as is */
   2056     res = PyObject_IsInstance(value, type);
   2057     if (res == -1)
   2058         return NULL;
   2059     if (res) {
   2060         Py_INCREF(value);
   2061         return value;
   2062     }
   2063 
   2064     dict = PyType_stgdict(type);
   2065     assert(dict);
   2066 
   2067     /* I think we can rely on this being a one-character string */
   2068     fmt = PyUnicode_AsUTF8(dict->proto);
   2069     assert(fmt);
   2070 
   2071     fd = _ctypes_get_fielddesc(fmt);
   2072     assert(fd);
   2073 
   2074     parg = PyCArgObject_new();
   2075     if (parg == NULL)
   2076         return NULL;
   2077 
   2078     parg->tag = fmt[0];
   2079     parg->pffi_type = fd->pffi_type;
   2080     parg->obj = fd->setfunc(&parg->value, value, 0);
   2081     if (parg->obj)
   2082         return (PyObject *)parg;
   2083     PyErr_Clear();
   2084     Py_DECREF(parg);
   2085 
   2086     as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
   2087     if (as_parameter) {
   2088         if (Py_EnterRecursiveCall("while processing _as_parameter_")) {
   2089             Py_DECREF(as_parameter);
   2090             return NULL;
   2091         }
   2092         value = PyCSimpleType_from_param(type, as_parameter);
   2093         Py_LeaveRecursiveCall();
   2094         Py_DECREF(as_parameter);
   2095         return value;
   2096     }
   2097     PyErr_SetString(PyExc_TypeError,
   2098                     "wrong type");
   2099     return NULL;
   2100 }
   2101 
   2102 static PyMethodDef PyCSimpleType_methods[] = {
   2103     { "from_param", PyCSimpleType_from_param, METH_O, from_param_doc },
   2104     { "from_address", CDataType_from_address, METH_O, from_address_doc },
   2105     { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
   2106     { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
   2107     { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
   2108     { NULL, NULL },
   2109 };
   2110 
   2111 PyTypeObject PyCSimpleType_Type = {
   2112     PyVarObject_HEAD_INIT(NULL, 0)
   2113     "_ctypes.PyCSimpleType",                                    /* tp_name */
   2114     0,                                          /* tp_basicsize */
   2115     0,                                          /* tp_itemsize */
   2116     0,                                          /* tp_dealloc */
   2117     0,                                          /* tp_print */
   2118     0,                                          /* tp_getattr */
   2119     0,                                          /* tp_setattr */
   2120     0,                                          /* tp_reserved */
   2121     0,                                          /* tp_repr */
   2122     0,                                          /* tp_as_number */
   2123     &CDataType_as_sequence,             /* tp_as_sequence */
   2124     0,                                          /* tp_as_mapping */
   2125     0,                                          /* tp_hash */
   2126     0,                                          /* tp_call */
   2127     0,                                          /* tp_str */
   2128     0,                                          /* tp_getattro */
   2129     0,                                          /* tp_setattro */
   2130     0,                                          /* tp_as_buffer */
   2131     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
   2132     "metatype for the PyCSimpleType Objects",           /* tp_doc */
   2133     0,                                          /* tp_traverse */
   2134     0,                                          /* tp_clear */
   2135     0,                                          /* tp_richcompare */
   2136     0,                                          /* tp_weaklistoffset */
   2137     0,                                          /* tp_iter */
   2138     0,                                          /* tp_iternext */
   2139     PyCSimpleType_methods,                      /* tp_methods */
   2140     0,                                          /* tp_members */
   2141     0,                                          /* tp_getset */
   2142     0,                                          /* tp_base */
   2143     0,                                          /* tp_dict */
   2144     0,                                          /* tp_descr_get */
   2145     0,                                          /* tp_descr_set */
   2146     0,                                          /* tp_dictoffset */
   2147     0,                                          /* tp_init */
   2148     0,                                          /* tp_alloc */
   2149     PyCSimpleType_new,                                  /* tp_new */
   2150     0,                                          /* tp_free */
   2151 };
   2152 
   2153 /******************************************************************/
   2154 /*
   2155   PyCFuncPtrType_Type
   2156  */
   2157 
   2158 static PyObject *
   2159 converters_from_argtypes(PyObject *ob)
   2160 {
   2161     PyObject *converters;
   2162     Py_ssize_t i;
   2163     Py_ssize_t nArgs;
   2164 
   2165     ob = PySequence_Tuple(ob); /* new reference */
   2166     if (!ob) {
   2167         PyErr_SetString(PyExc_TypeError,
   2168                         "_argtypes_ must be a sequence of types");
   2169         return NULL;
   2170     }
   2171 
   2172     nArgs = PyTuple_GET_SIZE(ob);
   2173     converters = PyTuple_New(nArgs);
   2174     if (!converters) {
   2175         Py_DECREF(ob);
   2176         return NULL;
   2177     }
   2178 
   2179     /* I have to check if this is correct. Using c_char, which has a size
   2180        of 1, will be assumed to be pushed as only one byte!
   2181        Aren't these promoted to integers by the C compiler and pushed as 4 bytes?
   2182     */
   2183 
   2184     for (i = 0; i < nArgs; ++i) {
   2185         PyObject *tp = PyTuple_GET_ITEM(ob, i);
   2186         PyObject *cnv = PyObject_GetAttrString(tp, "from_param");
   2187         if (!cnv)
   2188             goto argtypes_error_1;
   2189         PyTuple_SET_ITEM(converters, i, cnv);
   2190     }
   2191     Py_DECREF(ob);
   2192     return converters;
   2193 
   2194   argtypes_error_1:
   2195     Py_XDECREF(converters);
   2196     Py_DECREF(ob);
   2197     PyErr_Format(PyExc_TypeError,
   2198                  "item %zd in _argtypes_ has no from_param method",
   2199                  i+1);
   2200     return NULL;
   2201 }
   2202 
   2203 static int
   2204 make_funcptrtype_dict(StgDictObject *stgdict)
   2205 {
   2206     PyObject *ob;
   2207     PyObject *converters = NULL;
   2208 
   2209     stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment;
   2210     stgdict->length = 1;
   2211     stgdict->size = sizeof(void *);
   2212     stgdict->setfunc = NULL;
   2213     stgdict->getfunc = NULL;
   2214     stgdict->ffi_type_pointer = ffi_type_pointer;
   2215 
   2216     ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_");
   2217     if (!ob || !PyLong_Check(ob)) {
   2218         PyErr_SetString(PyExc_TypeError,
   2219             "class must define _flags_ which must be an integer");
   2220         return -1;
   2221     }
   2222     stgdict->flags = PyLong_AS_LONG(ob) | TYPEFLAG_ISPOINTER;
   2223 
   2224     /* _argtypes_ is optional... */
   2225     ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_");
   2226     if (ob) {
   2227         converters = converters_from_argtypes(ob);
   2228         if (!converters)
   2229             goto error;
   2230         Py_INCREF(ob);
   2231         stgdict->argtypes = ob;
   2232         stgdict->converters = converters;
   2233     }
   2234 
   2235     ob = PyDict_GetItemString((PyObject *)stgdict, "_restype_");
   2236     if (ob) {
   2237         if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) {
   2238             PyErr_SetString(PyExc_TypeError,
   2239                 "_restype_ must be a type, a callable, or None");
   2240             return -1;
   2241         }
   2242         Py_INCREF(ob);
   2243         stgdict->restype = ob;
   2244         stgdict->checker = PyObject_GetAttrString(ob, "_check_retval_");
   2245         if (stgdict->checker == NULL)
   2246             PyErr_Clear();
   2247     }
   2248 /* XXX later, maybe.
   2249     ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_");
   2250     if (ob) {
   2251         if (!PyCallable_Check(ob)) {
   2252             PyErr_SetString(PyExc_TypeError,
   2253                 "_errcheck_ must be callable");
   2254             return -1;
   2255         }
   2256         Py_INCREF(ob);
   2257         stgdict->errcheck = ob;
   2258     }
   2259 */
   2260     return 0;
   2261 
   2262   error:
   2263     Py_XDECREF(converters);
   2264     return -1;
   2265 
   2266 }
   2267 
   2268 static PyCArgObject *
   2269 PyCFuncPtrType_paramfunc(CDataObject *self)
   2270 {
   2271     PyCArgObject *parg;
   2272 
   2273     parg = PyCArgObject_new();
   2274     if (parg == NULL)
   2275         return NULL;
   2276 
   2277     parg->tag = 'P';
   2278     parg->pffi_type = &ffi_type_pointer;
   2279     Py_INCREF(self);
   2280     parg->obj = (PyObject *)self;
   2281     parg->value.p = *(void **)self->b_ptr;
   2282     return parg;
   2283 }
   2284 
   2285 static PyObject *
   2286 PyCFuncPtrType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
   2287 {
   2288     PyTypeObject *result;
   2289     StgDictObject *stgdict;
   2290 
   2291     stgdict = (StgDictObject *)PyObject_CallObject(
   2292         (PyObject *)&PyCStgDict_Type, NULL);
   2293     if (!stgdict)
   2294         return NULL;
   2295 
   2296     stgdict->paramfunc = PyCFuncPtrType_paramfunc;
   2297     /* We do NOT expose the function signature in the format string.  It
   2298        is impossible, generally, because the only requirement for the
   2299        argtypes items is that they have a .from_param method - we do not
   2300        know the types of the arguments (although, in practice, most
   2301        argtypes would be a ctypes type).
   2302     */
   2303     stgdict->format = _ctypes_alloc_format_string(NULL, "X{}");
   2304     if (stgdict->format == NULL) {
   2305         Py_DECREF((PyObject *)stgdict);
   2306         return NULL;
   2307     }
   2308     stgdict->flags |= TYPEFLAG_ISPOINTER;
   2309 
   2310     /* create the new instance (which is a class,
   2311        since we are a metatype!) */
   2312     result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
   2313     if (result == NULL) {
   2314         Py_DECREF((PyObject *)stgdict);
   2315         return NULL;
   2316     }
   2317 
   2318     /* replace the class dict by our updated storage dict */
   2319     if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
   2320         Py_DECREF(result);
   2321         Py_DECREF((PyObject *)stgdict);
   2322         return NULL;
   2323     }
   2324     Py_SETREF(result->tp_dict, (PyObject *)stgdict);
   2325 
   2326     if (-1 == make_funcptrtype_dict(stgdict)) {
   2327         Py_DECREF(result);
   2328         return NULL;
   2329     }
   2330 
   2331     return (PyObject *)result;
   2332 }
   2333 
   2334 PyTypeObject PyCFuncPtrType_Type = {
   2335     PyVarObject_HEAD_INIT(NULL, 0)
   2336     "_ctypes.PyCFuncPtrType",                           /* tp_name */
   2337     0,                                          /* tp_basicsize */
   2338     0,                                          /* tp_itemsize */
   2339     0,                                          /* tp_dealloc */
   2340     0,                                          /* tp_print */
   2341     0,                                          /* tp_getattr */
   2342     0,                                          /* tp_setattr */
   2343     0,                                          /* tp_reserved */
   2344     0,                                          /* tp_repr */
   2345     0,                                          /* tp_as_number */
   2346     &CDataType_as_sequence,                     /* tp_as_sequence */
   2347     0,                                          /* tp_as_mapping */
   2348     0,                                          /* tp_hash */
   2349     0,                                          /* tp_call */
   2350     0,                                          /* tp_str */
   2351     0,                                          /* tp_getattro */
   2352     0,                                          /* tp_setattro */
   2353     0,                                          /* tp_as_buffer */
   2354     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
   2355     "metatype for C function pointers",         /* tp_doc */
   2356     (traverseproc)CDataType_traverse,           /* tp_traverse */
   2357     (inquiry)CDataType_clear,                   /* tp_clear */
   2358     0,                                          /* tp_richcompare */
   2359     0,                                          /* tp_weaklistoffset */
   2360     0,                                          /* tp_iter */
   2361     0,                                          /* tp_iternext */
   2362     CDataType_methods,                          /* tp_methods */
   2363     0,                                          /* tp_members */
   2364     0,                                          /* tp_getset */
   2365     0,                                          /* tp_base */
   2366     0,                                          /* tp_dict */
   2367     0,                                          /* tp_descr_get */
   2368     0,                                          /* tp_descr_set */
   2369     0,                                          /* tp_dictoffset */
   2370     0,                                          /* tp_init */
   2371     0,                                          /* tp_alloc */
   2372     PyCFuncPtrType_new,                         /* tp_new */
   2373     0,                                          /* tp_free */
   2374 };
   2375 
   2376 
   2377 /*****************************************************************
   2378  * Code to keep needed objects alive
   2379  */
   2380 
   2381 static CDataObject *
   2382 PyCData_GetContainer(CDataObject *self)
   2383 {
   2384     while (self->b_base)
   2385         self = self->b_base;
   2386     if (self->b_objects == NULL) {
   2387         if (self->b_length) {
   2388             self->b_objects = PyDict_New();
   2389             if (self->b_objects == NULL)
   2390                 return NULL;
   2391         } else {
   2392             Py_INCREF(Py_None);
   2393             self->b_objects = Py_None;
   2394         }
   2395     }
   2396     return self;
   2397 }
   2398 
   2399 static PyObject *
   2400 GetKeepedObjects(CDataObject *target)
   2401 {
   2402     CDataObject *container;
   2403     container = PyCData_GetContainer(target);
   2404     if (container == NULL)
   2405         return NULL;
   2406     return container->b_objects;
   2407 }
   2408 
   2409 static PyObject *
   2410 unique_key(CDataObject *target, Py_ssize_t index)
   2411 {
   2412     char string[256];
   2413     char *cp = string;
   2414     size_t bytes_left;
   2415 
   2416     Py_BUILD_ASSERT(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2);
   2417     cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
   2418     while (target->b_base) {
   2419         bytes_left = sizeof(string) - (cp - string) - 1;
   2420         /* Hex format needs 2 characters per byte */
   2421         if (bytes_left < sizeof(Py_ssize_t) * 2) {
   2422             PyErr_SetString(PyExc_ValueError,
   2423                             "ctypes object structure too deep");
   2424             return NULL;
   2425         }
   2426         cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int));
   2427         target = target->b_base;
   2428     }
   2429     return PyUnicode_FromStringAndSize(string, cp-string);
   2430 }
   2431 
   2432 /*
   2433  * Keep a reference to 'keep' in the 'target', at index 'index'.
   2434  *
   2435  * If 'keep' is None, do nothing.
   2436  *
   2437  * Otherwise create a dictionary (if it does not yet exist) id the root
   2438  * objects 'b_objects' item, which will store the 'keep' object under a unique
   2439  * key.
   2440  *
   2441  * The unique_key helper travels the target's b_base pointer down to the root,
   2442  * building a string containing hex-formatted indexes found during traversal,
   2443  * separated by colons.
   2444  *
   2445  * The index tuple is used as a key into the root object's b_objects dict.
   2446  *
   2447  * Note: This function steals a refcount of the third argument, even if it
   2448  * fails!
   2449  */
   2450 static int
   2451 KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep)
   2452 {
   2453     int result;
   2454     CDataObject *ob;
   2455     PyObject *key;
   2456 
   2457 /* Optimization: no need to store None */
   2458     if (keep == Py_None) {
   2459         Py_DECREF(Py_None);
   2460         return 0;
   2461     }
   2462     ob = PyCData_GetContainer(target);
   2463     if (ob == NULL) {
   2464         Py_DECREF(keep);
   2465         return -1;
   2466     }
   2467     if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) {
   2468         Py_XSETREF(ob->b_objects, keep); /* refcount consumed */
   2469         return 0;
   2470     }
   2471     key = unique_key(target, index);
   2472     if (key == NULL) {
   2473         Py_DECREF(keep);
   2474         return -1;
   2475     }
   2476     result = PyDict_SetItem(ob->b_objects, key, keep);
   2477     Py_DECREF(key);
   2478     Py_DECREF(keep);
   2479     return result;
   2480 }
   2481 
   2482 /******************************************************************/
   2483 /*
   2484   PyCData_Type
   2485  */
   2486 static int
   2487 PyCData_traverse(CDataObject *self, visitproc visit, void *arg)
   2488 {
   2489     Py_VISIT(self->b_objects);
   2490     Py_VISIT((PyObject *)self->b_base);
   2491     return 0;
   2492 }
   2493 
   2494 static int
   2495 PyCData_clear(CDataObject *self)
   2496 {
   2497     Py_CLEAR(self->b_objects);
   2498     if ((self->b_needsfree)
   2499         && _CDataObject_HasExternalBuffer(self))
   2500         PyMem_Free(self->b_ptr);
   2501     self->b_ptr = NULL;
   2502     Py_CLEAR(self->b_base);
   2503     return 0;
   2504 }
   2505 
   2506 static void
   2507 PyCData_dealloc(PyObject *self)
   2508 {
   2509     PyCData_clear((CDataObject *)self);
   2510     Py_TYPE(self)->tp_free(self);
   2511 }
   2512 
   2513 static PyMemberDef PyCData_members[] = {
   2514     { "_b_base_", T_OBJECT,
   2515       offsetof(CDataObject, b_base), READONLY,
   2516       "the base object" },
   2517     { "_b_needsfree_", T_INT,
   2518       offsetof(CDataObject, b_needsfree), READONLY,
   2519       "whether the object owns the memory or not" },
   2520     { "_objects", T_OBJECT,
   2521       offsetof(CDataObject, b_objects), READONLY,
   2522       "internal objects tree (NEVER CHANGE THIS OBJECT!)"},
   2523     { NULL },
   2524 };
   2525 
   2526 static int PyCData_NewGetBuffer(PyObject *myself, Py_buffer *view, int flags)
   2527 {
   2528     CDataObject *self = (CDataObject *)myself;
   2529     StgDictObject *dict = PyObject_stgdict(myself);
   2530     Py_ssize_t i;
   2531 
   2532     if (view == NULL) return 0;
   2533 
   2534     view->buf = self->b_ptr;
   2535     view->obj = myself;
   2536     Py_INCREF(myself);
   2537     view->len = self->b_size;
   2538     view->readonly = 0;
   2539     /* use default format character if not set */
   2540     view->format = dict->format ? dict->format : "B";
   2541     view->ndim = dict->ndim;
   2542     view->shape = dict->shape;
   2543     view->itemsize = self->b_size;
   2544     if (view->itemsize) {
   2545         for (i = 0; i < view->ndim; ++i) {
   2546             view->itemsize /= dict->shape[i];
   2547         }
   2548     }
   2549     view->strides = NULL;
   2550     view->suboffsets = NULL;
   2551     view->internal = NULL;
   2552     return 0;
   2553 }
   2554 
   2555 static PyBufferProcs PyCData_as_buffer = {
   2556     PyCData_NewGetBuffer,
   2557     NULL,
   2558 };
   2559 
   2560 /*
   2561  * CData objects are mutable, so they cannot be hashable!
   2562  */
   2563 static Py_hash_t
   2564 PyCData_nohash(PyObject *self)
   2565 {
   2566     PyErr_SetString(PyExc_TypeError, "unhashable type");
   2567     return -1;
   2568 }
   2569 
   2570 static PyObject *
   2571 PyCData_reduce(PyObject *myself, PyObject *args)
   2572 {
   2573     CDataObject *self = (CDataObject *)myself;
   2574 
   2575     if (PyObject_stgdict(myself)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) {
   2576         PyErr_SetString(PyExc_ValueError,
   2577                         "ctypes objects containing pointers cannot be pickled");
   2578         return NULL;
   2579     }
   2580     return Py_BuildValue("O(O(NN))",
   2581                          _unpickle,
   2582                          Py_TYPE(myself),
   2583                          PyObject_GetAttrString(myself, "__dict__"),
   2584                          PyBytes_FromStringAndSize(self->b_ptr, self->b_size));
   2585 }
   2586 
   2587 static PyObject *
   2588 PyCData_setstate(PyObject *myself, PyObject *args)
   2589 {
   2590     void *data;
   2591     Py_ssize_t len;
   2592     int res;
   2593     PyObject *dict, *mydict;
   2594     CDataObject *self = (CDataObject *)myself;
   2595     if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len))
   2596         return NULL;
   2597     if (len > self->b_size)
   2598         len = self->b_size;
   2599     memmove(self->b_ptr, data, len);
   2600     mydict = PyObject_GetAttrString(myself, "__dict__");
   2601     res = PyDict_Update(mydict, dict);
   2602     Py_DECREF(mydict);
   2603     if (res == -1)
   2604         return NULL;
   2605     Py_INCREF(Py_None);
   2606     return Py_None;
   2607 }
   2608 
   2609 /*
   2610  * default __ctypes_from_outparam__ method returns self.
   2611  */
   2612 static PyObject *
   2613 PyCData_from_outparam(PyObject *self, PyObject *args)
   2614 {
   2615     Py_INCREF(self);
   2616     return self;
   2617 }
   2618 
   2619 static PyMethodDef PyCData_methods[] = {
   2620     { "__ctypes_from_outparam__", PyCData_from_outparam, METH_NOARGS, },
   2621     { "__reduce__", PyCData_reduce, METH_NOARGS, },
   2622     { "__setstate__", PyCData_setstate, METH_VARARGS, },
   2623     { NULL, NULL },
   2624 };
   2625 
   2626 PyTypeObject PyCData_Type = {
   2627     PyVarObject_HEAD_INIT(NULL, 0)
   2628     "_ctypes._CData",
   2629     sizeof(CDataObject),                        /* tp_basicsize */
   2630     0,                                          /* tp_itemsize */
   2631     PyCData_dealloc,                                    /* tp_dealloc */
   2632     0,                                          /* tp_print */
   2633     0,                                          /* tp_getattr */
   2634     0,                                          /* tp_setattr */
   2635     0,                                          /* tp_reserved */
   2636     0,                                          /* tp_repr */
   2637     0,                                          /* tp_as_number */
   2638     0,                                          /* tp_as_sequence */
   2639     0,                                          /* tp_as_mapping */
   2640     PyCData_nohash,                             /* tp_hash */
   2641     0,                                          /* tp_call */
   2642     0,                                          /* tp_str */
   2643     0,                                          /* tp_getattro */
   2644     0,                                          /* tp_setattro */
   2645     &PyCData_as_buffer,                         /* tp_as_buffer */
   2646     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
   2647     "XXX to be provided",                       /* tp_doc */
   2648     (traverseproc)PyCData_traverse,             /* tp_traverse */
   2649     (inquiry)PyCData_clear,                     /* tp_clear */
   2650     0,                                          /* tp_richcompare */
   2651     0,                                          /* tp_weaklistoffset */
   2652     0,                                          /* tp_iter */
   2653     0,                                          /* tp_iternext */
   2654     PyCData_methods,                                    /* tp_methods */
   2655     PyCData_members,                                    /* tp_members */
   2656     0,                                          /* tp_getset */
   2657     0,                                          /* tp_base */
   2658     0,                                          /* tp_dict */
   2659     0,                                          /* tp_descr_get */
   2660     0,                                          /* tp_descr_set */
   2661     0,                                          /* tp_dictoffset */
   2662     0,                                          /* tp_init */
   2663     0,                                          /* tp_alloc */
   2664     0,                                          /* tp_new */
   2665     0,                                          /* tp_free */
   2666 };
   2667 
   2668 static int PyCData_MallocBuffer(CDataObject *obj, StgDictObject *dict)
   2669 {
   2670     if ((size_t)dict->size <= sizeof(obj->b_value)) {
   2671         /* No need to call malloc, can use the default buffer */
   2672         obj->b_ptr = (char *)&obj->b_value;
   2673         /* The b_needsfree flag does not mean that we actually did
   2674            call PyMem_Malloc to allocate the memory block; instead it
   2675            means we are the *owner* of the memory and are responsible
   2676            for freeing resources associated with the memory.  This is
   2677            also the reason that b_needsfree is exposed to Python.
   2678          */
   2679         obj->b_needsfree = 1;
   2680     } else {
   2681         /* In python 2.4, and ctypes 0.9.6, the malloc call took about
   2682            33% of the creation time for c_int().
   2683         */
   2684         obj->b_ptr = (char *)PyMem_Malloc(dict->size);
   2685         if (obj->b_ptr == NULL) {
   2686             PyErr_NoMemory();
   2687             return -1;
   2688         }
   2689         obj->b_needsfree = 1;
   2690         memset(obj->b_ptr, 0, dict->size);
   2691     }
   2692     obj->b_size = dict->size;
   2693     return 0;
   2694 }
   2695 
   2696 PyObject *
   2697 PyCData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr)
   2698 {
   2699     CDataObject *cmem;
   2700     StgDictObject *dict;
   2701 
   2702     assert(PyType_Check(type));
   2703     dict = PyType_stgdict(type);
   2704     if (!dict) {
   2705         PyErr_SetString(PyExc_TypeError,
   2706                         "abstract class");
   2707         return NULL;
   2708     }
   2709     dict->flags |= DICTFLAG_FINAL;
   2710     cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0);
   2711     if (cmem == NULL)
   2712         return NULL;
   2713     assert(CDataObject_Check(cmem));
   2714 
   2715     cmem->b_length = dict->length;
   2716     cmem->b_size = dict->size;
   2717     if (base) { /* use base's buffer */
   2718         assert(CDataObject_Check(base));
   2719         cmem->b_ptr = adr;
   2720         cmem->b_needsfree = 0;
   2721         Py_INCREF(base);
   2722         cmem->b_base = (CDataObject *)base;
   2723         cmem->b_index = index;
   2724     } else { /* copy contents of adr */
   2725         if (-1 == PyCData_MallocBuffer(cmem, dict)) {
   2726             Py_DECREF(cmem);
   2727             return NULL;
   2728         }
   2729         memcpy(cmem->b_ptr, adr, dict->size);
   2730         cmem->b_index = index;
   2731     }
   2732     return (PyObject *)cmem;
   2733 }
   2734 
   2735 /*
   2736  Box a memory block into a CData instance.
   2737 */
   2738 PyObject *
   2739 PyCData_AtAddress(PyObject *type, void *buf)
   2740 {
   2741     CDataObject *pd;
   2742     StgDictObject *dict;
   2743 
   2744     assert(PyType_Check(type));
   2745     dict = PyType_stgdict(type);
   2746     if (!dict) {
   2747         PyErr_SetString(PyExc_TypeError,
   2748                         "abstract class");
   2749         return NULL;
   2750     }
   2751     dict->flags |= DICTFLAG_FINAL;
   2752 
   2753     pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0);
   2754     if (!pd)
   2755         return NULL;
   2756     assert(CDataObject_Check(pd));
   2757     pd->b_ptr = (char *)buf;
   2758     pd->b_length = dict->length;
   2759     pd->b_size = dict->size;
   2760     return (PyObject *)pd;
   2761 }
   2762 
   2763 /*
   2764   This function returns TRUE for c_int, c_void_p, and these kind of
   2765   classes.  FALSE otherwise FALSE also for subclasses of c_int and
   2766   such.
   2767 */
   2768 int _ctypes_simple_instance(PyObject *obj)
   2769 {
   2770     PyTypeObject *type = (PyTypeObject *)obj;
   2771 
   2772     if (PyCSimpleTypeObject_Check(type))
   2773         return type->tp_base != &Simple_Type;
   2774     return 0;
   2775 }
   2776 
   2777 PyObject *
   2778 PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src,
   2779           Py_ssize_t index, Py_ssize_t size, char *adr)
   2780 {
   2781     StgDictObject *dict;
   2782     if (getfunc)
   2783         return getfunc(adr, size);
   2784     assert(type);
   2785     dict = PyType_stgdict(type);
   2786     if (dict && dict->getfunc && !_ctypes_simple_instance(type))
   2787         return dict->getfunc(adr, size);
   2788     return PyCData_FromBaseObj(type, src, index, adr);
   2789 }
   2790 
   2791 /*
   2792   Helper function for PyCData_set below.
   2793 */
   2794 static PyObject *
   2795 _PyCData_set(CDataObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
   2796            Py_ssize_t size, char *ptr)
   2797 {
   2798     CDataObject *src;
   2799     int err;
   2800 
   2801     if (setfunc)
   2802         return setfunc(ptr, value, size);
   2803 
   2804     if (!CDataObject_Check(value)) {
   2805         StgDictObject *dict = PyType_stgdict(type);
   2806         if (dict && dict->setfunc)
   2807             return dict->setfunc(ptr, value, size);
   2808         /*
   2809            If value is a tuple, we try to call the type with the tuple
   2810            and use the result!
   2811         */
   2812         assert(PyType_Check(type));
   2813         if (PyTuple_Check(value)) {
   2814             PyObject *ob;
   2815             PyObject *result;
   2816             ob = PyObject_CallObject(type, value);
   2817             if (ob == NULL) {
   2818                 _ctypes_extend_error(PyExc_RuntimeError, "(%s) ",
   2819                                   ((PyTypeObject *)type)->tp_name);
   2820                 return NULL;
   2821             }
   2822             result = _PyCData_set(dst, type, setfunc, ob,
   2823                                 size, ptr);
   2824             Py_DECREF(ob);
   2825             return result;
   2826         } else if (value == Py_None && PyCPointerTypeObject_Check(type)) {
   2827             *(void **)ptr = NULL;
   2828             Py_INCREF(Py_None);
   2829             return Py_None;
   2830         } else {
   2831             PyErr_Format(PyExc_TypeError,
   2832                          "expected %s instance, got %s",
   2833                          ((PyTypeObject *)type)->tp_name,
   2834                          Py_TYPE(value)->tp_name);
   2835             return NULL;
   2836         }
   2837     }
   2838     src = (CDataObject *)value;
   2839 
   2840     err = PyObject_IsInstance(value, type);
   2841     if (err == -1)
   2842         return NULL;
   2843     if (err) {
   2844         memcpy(ptr,
   2845                src->b_ptr,
   2846                size);
   2847 
   2848         if (PyCPointerTypeObject_Check(type)) {
   2849             /* XXX */
   2850         }
   2851 
   2852         value = GetKeepedObjects(src);
   2853         if (value == NULL)
   2854             return NULL;
   2855 
   2856         Py_INCREF(value);
   2857         return value;
   2858     }
   2859 
   2860     if (PyCPointerTypeObject_Check(type)
   2861         && ArrayObject_Check(value)) {
   2862         StgDictObject *p1, *p2;
   2863         PyObject *keep;
   2864         p1 = PyObject_stgdict(value);
   2865         assert(p1); /* Cannot be NULL for array instances */
   2866         p2 = PyType_stgdict(type);
   2867         assert(p2); /* Cannot be NULL for pointer types */
   2868 
   2869         if (p1->proto != p2->proto) {
   2870             PyErr_Format(PyExc_TypeError,
   2871                          "incompatible types, %s instance instead of %s instance",
   2872                          Py_TYPE(value)->tp_name,
   2873                          ((PyTypeObject *)type)->tp_name);
   2874             return NULL;
   2875         }
   2876         *(void **)ptr = src->b_ptr;
   2877 
   2878         keep = GetKeepedObjects(src);
   2879         if (keep == NULL)
   2880             return NULL;
   2881 
   2882         /*
   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!
   2889         */
   2890         return PyTuple_Pack(2, keep, value);
   2891     }
   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);
   2896     return NULL;
   2897 }
   2898 
   2899 /*
   2900  * Set a slice in object 'dst', which has the type 'type',
   2901  * to the value 'value'.
   2902  */
   2903 int
   2904 PyCData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
   2905           Py_ssize_t index, Py_ssize_t size, char *ptr)
   2906 {
   2907     CDataObject *mem = (CDataObject *)dst;
   2908     PyObject *result;
   2909 
   2910     if (!CDataObject_Check(dst)) {
   2911         PyErr_SetString(PyExc_TypeError,
   2912                         "not a ctype instance");
   2913         return -1;
   2914     }
   2915 
   2916     result = _PyCData_set(mem, type, setfunc, value,
   2917                         size, ptr);
   2918     if (result == NULL)
   2919         return -1;
   2920 
   2921     /* KeepRef steals a refcount from it's last argument */
   2922     /* If KeepRef fails, we are stumped.  The dst memory block has already
   2923        been changed */
   2924     return KeepRef(mem, index, result);
   2925 }
   2926 
   2927 
   2928 /******************************************************************/
   2929 static PyObject *
   2930 GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
   2931 {
   2932     CDataObject *obj;
   2933     StgDictObject *dict;
   2934 
   2935     dict = PyType_stgdict((PyObject *)type);
   2936     if (!dict) {
   2937         PyErr_SetString(PyExc_TypeError,
   2938                         "abstract class");
   2939         return NULL;
   2940     }
   2941     dict->flags |= DICTFLAG_FINAL;
   2942 
   2943     obj = (CDataObject *)type->tp_alloc(type, 0);
   2944     if (!obj)
   2945         return NULL;
   2946 
   2947     obj->b_base = NULL;
   2948     obj->b_index = 0;
   2949     obj->b_objects = NULL;
   2950     obj->b_length = dict->length;
   2951 
   2952     if (-1 == PyCData_MallocBuffer(obj, dict)) {
   2953         Py_DECREF(obj);
   2954         return NULL;
   2955     }
   2956     return (PyObject *)obj;
   2957 }
   2958 /*****************************************************************/
   2959 /*
   2960   PyCFuncPtr_Type
   2961 */
   2962 
   2963 static int
   2964 PyCFuncPtr_set_errcheck(PyCFuncPtrObject *self, PyObject *ob)
   2965 {
   2966     if (ob && !PyCallable_Check(ob)) {
   2967         PyErr_SetString(PyExc_TypeError,
   2968                         "the errcheck attribute must be callable");
   2969         return -1;
   2970     }
   2971     Py_XINCREF(ob);
   2972     Py_XSETREF(self->errcheck, ob);
   2973     return 0;
   2974 }
   2975 
   2976 static PyObject *
   2977 PyCFuncPtr_get_errcheck(PyCFuncPtrObject *self)
   2978 {
   2979     if (self->errcheck) {
   2980         Py_INCREF(self->errcheck);
   2981         return self->errcheck;
   2982     }
   2983     Py_INCREF(Py_None);
   2984     return Py_None;
   2985 }
   2986 
   2987 static int
   2988 PyCFuncPtr_set_restype(PyCFuncPtrObject *self, PyObject *ob)
   2989 {
   2990     if (ob == NULL) {
   2991         Py_CLEAR(self->restype);
   2992         Py_CLEAR(self->checker);
   2993         return 0;
   2994     }
   2995     if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) {
   2996         PyErr_SetString(PyExc_TypeError,
   2997                         "restype must be a type, a callable, or None");
   2998         return -1;
   2999     }
   3000     Py_INCREF(ob);
   3001     Py_XSETREF(self->restype, ob);
   3002     Py_XSETREF(self->checker, PyObject_GetAttrString(ob, "_check_retval_"));
   3003     if (self->checker == NULL)
   3004         PyErr_Clear();
   3005     return 0;
   3006 }
   3007 
   3008 static PyObject *
   3009 PyCFuncPtr_get_restype(PyCFuncPtrObject *self)
   3010 {
   3011     StgDictObject *dict;
   3012     if (self->restype) {
   3013         Py_INCREF(self->restype);
   3014         return self->restype;
   3015     }
   3016     dict = PyObject_stgdict((PyObject *)self);
   3017     assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
   3018     if (dict->restype) {
   3019         Py_INCREF(dict->restype);
   3020         return dict->restype;
   3021     } else {
   3022         Py_INCREF(Py_None);
   3023         return Py_None;
   3024     }
   3025 }
   3026 
   3027 static int
   3028 PyCFuncPtr_set_argtypes(PyCFuncPtrObject *self, PyObject *ob)
   3029 {
   3030     PyObject *converters;
   3031 
   3032     if (ob == NULL || ob == Py_None) {
   3033         Py_CLEAR(self->converters);
   3034         Py_CLEAR(self->argtypes);
   3035     } else {
   3036         converters = converters_from_argtypes(ob);
   3037         if (!converters)
   3038             return -1;
   3039         Py_XSETREF(self->converters, converters);
   3040         Py_INCREF(ob);
   3041         Py_XSETREF(self->argtypes, ob);
   3042     }
   3043     return 0;
   3044 }
   3045 
   3046 static PyObject *
   3047 PyCFuncPtr_get_argtypes(PyCFuncPtrObject *self)
   3048 {
   3049     StgDictObject *dict;
   3050     if (self->argtypes) {
   3051         Py_INCREF(self->argtypes);
   3052         return self->argtypes;
   3053     }
   3054     dict = PyObject_stgdict((PyObject *)self);
   3055     assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
   3056     if (dict->argtypes) {
   3057         Py_INCREF(dict->argtypes);
   3058         return dict->argtypes;
   3059     } else {
   3060         Py_INCREF(Py_None);
   3061         return Py_None;
   3062     }
   3063 }
   3064 
   3065 static PyGetSetDef PyCFuncPtr_getsets[] = {
   3066     { "errcheck", (getter)PyCFuncPtr_get_errcheck, (setter)PyCFuncPtr_set_errcheck,
   3067       "a function to check for errors", NULL },
   3068     { "restype", (getter)PyCFuncPtr_get_restype, (setter)PyCFuncPtr_set_restype,
   3069       "specify the result type", NULL },
   3070     { "argtypes", (getter)PyCFuncPtr_get_argtypes,
   3071       (setter)PyCFuncPtr_set_argtypes,
   3072       "specify the argument types", NULL },
   3073     { NULL, NULL }
   3074 };
   3075 
   3076 #ifdef MS_WIN32
   3077 static PPROC FindAddress(void *handle, const char *name, PyObject *type)
   3078 {
   3079 #ifdef MS_WIN64
   3080     /* win64 has no stdcall calling conv, so it should
   3081        also not have the name mangling of it.
   3082     */
   3083     return (PPROC)GetProcAddress(handle, name);
   3084 #else
   3085     PPROC address;
   3086     char *mangled_name;
   3087     int i;
   3088     StgDictObject *dict;
   3089 
   3090     address = (PPROC)GetProcAddress(handle, name);
   3091     if (address)
   3092         return address;
   3093     if (((size_t)name & ~0xFFFF) == 0) {
   3094         return NULL;
   3095     }
   3096 
   3097     dict = PyType_stgdict((PyObject *)type);
   3098     /* It should not happen that dict is NULL, but better be safe */
   3099     if (dict==NULL || dict->flags & FUNCFLAG_CDECL)
   3100         return address;
   3101 
   3102     /* for stdcall, try mangled names:
   3103        funcname -> _funcname@<n>
   3104        where n is 0, 4, 8, 12, ..., 128
   3105      */
   3106     mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */
   3107     if (!mangled_name)
   3108         return NULL;
   3109     for (i = 0; i < 32; ++i) {
   3110         sprintf(mangled_name, "_%s@%d", name, i*4);
   3111         address = (PPROC)GetProcAddress(handle, mangled_name);
   3112         if (address)
   3113             return address;
   3114     }
   3115     return NULL;
   3116 #endif
   3117 }
   3118 #endif
   3119 
   3120 /* Return 1 if usable, 0 else and exception set. */
   3121 static int
   3122 _check_outarg_type(PyObject *arg, Py_ssize_t index)
   3123 {
   3124     StgDictObject *dict;
   3125 
   3126     if (PyCPointerTypeObject_Check(arg))
   3127         return 1;
   3128 
   3129     if (PyCArrayTypeObject_Check(arg))
   3130         return 1;
   3131 
   3132     dict = PyType_stgdict(arg);
   3133     if (dict
   3134         /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
   3135         && PyUnicode_Check(dict->proto)
   3136 /* We only allow c_void_p, c_char_p and c_wchar_p as a simple output parameter type */
   3137         && (strchr("PzZ", PyUnicode_AsUTF8(dict->proto)[0]))) {
   3138         return 1;
   3139     }
   3140 
   3141     PyErr_Format(PyExc_TypeError,
   3142                  "'out' parameter %d must be a pointer type, not %s",
   3143                  Py_SAFE_DOWNCAST(index, Py_ssize_t, int),
   3144                  PyType_Check(arg) ?
   3145                  ((PyTypeObject *)arg)->tp_name :
   3146              Py_TYPE(arg)->tp_name);
   3147     return 0;
   3148 }
   3149 
   3150 /* Returns 1 on success, 0 on error */
   3151 static int
   3152 _validate_paramflags(PyTypeObject *type, PyObject *paramflags)
   3153 {
   3154     Py_ssize_t i, len;
   3155     StgDictObject *dict;
   3156     PyObject *argtypes;
   3157 
   3158     dict = PyType_stgdict((PyObject *)type);
   3159     assert(dict); /* Cannot be NULL. 'type' is a PyCFuncPtr type. */
   3160     argtypes = dict->argtypes;
   3161 
   3162     if (paramflags == NULL || dict->argtypes == NULL)
   3163         return 1;
   3164 
   3165     if (!PyTuple_Check(paramflags)) {
   3166         PyErr_SetString(PyExc_TypeError,
   3167                         "paramflags must be a tuple or None");
   3168         return 0;
   3169     }
   3170 
   3171     len = PyTuple_GET_SIZE(paramflags);
   3172     if (len != PyTuple_GET_SIZE(dict->argtypes)) {
   3173         PyErr_SetString(PyExc_ValueError,
   3174                         "paramflags must have the same length as argtypes");
   3175         return 0;
   3176     }
   3177 
   3178     for (i = 0; i < len; ++i) {
   3179         PyObject *item = PyTuple_GET_ITEM(paramflags, i);
   3180         int flag;
   3181         char *name;
   3182         PyObject *defval;
   3183         PyObject *typ;
   3184         if (!PyArg_ParseTuple(item, "i|ZO", &flag, &name, &defval)) {
   3185             PyErr_SetString(PyExc_TypeError,
   3186                    "paramflags must be a sequence of (int [,string [,value]]) tuples");
   3187             return 0;
   3188         }
   3189         typ = PyTuple_GET_ITEM(argtypes, i);
   3190         switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
   3191         case 0:
   3192         case PARAMFLAG_FIN:
   3193         case PARAMFLAG_FIN | PARAMFLAG_FLCID:
   3194         case PARAMFLAG_FIN | PARAMFLAG_FOUT:
   3195             break;
   3196         case PARAMFLAG_FOUT:
   3197             if (!_check_outarg_type(typ, i+1))
   3198                 return 0;
   3199             break;
   3200         default:
   3201             PyErr_Format(PyExc_TypeError,
   3202                          "paramflag value %d not supported",
   3203                          flag);
   3204             return 0;
   3205         }
   3206     }
   3207     return 1;
   3208 }
   3209 
   3210 static int
   3211 _get_name(PyObject *obj, const char **pname)
   3212 {
   3213 #ifdef MS_WIN32
   3214     if (PyLong_Check(obj)) {
   3215         /* We have to use MAKEINTRESOURCEA for Windows CE.
   3216            Works on Windows as well, of course.
   3217         */
   3218         *pname = MAKEINTRESOURCEA(PyLong_AsUnsignedLongMask(obj) & 0xFFFF);
   3219         return 1;
   3220     }
   3221 #endif
   3222     if (PyBytes_Check(obj)) {
   3223         *pname = PyBytes_AS_STRING(obj);
   3224         return *pname ? 1 : 0;
   3225     }
   3226     if (PyUnicode_Check(obj)) {
   3227         *pname = PyUnicode_AsUTF8(obj);
   3228         return *pname ? 1 : 0;
   3229     }
   3230     PyErr_SetString(PyExc_TypeError,
   3231                     "function name must be string, bytes object or integer");
   3232     return 0;
   3233 }
   3234 
   3235 
   3236 static PyObject *
   3237 PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
   3238 {
   3239     const char *name;
   3240     int (* address)(void);
   3241     PyObject *ftuple;
   3242     PyObject *dll;
   3243     PyObject *obj;
   3244     PyCFuncPtrObject *self;
   3245     void *handle;
   3246     PyObject *paramflags = NULL;
   3247 
   3248     if (!PyArg_ParseTuple(args, "O|O", &ftuple, &paramflags))
   3249         return NULL;
   3250     if (paramflags == Py_None)
   3251         paramflags = NULL;
   3252 
   3253     ftuple = PySequence_Tuple(ftuple);
   3254     if (!ftuple)
   3255         /* Here ftuple is a borrowed reference */
   3256         return NULL;
   3257 
   3258     if (!PyArg_ParseTuple(ftuple, "O&O", _get_name, &name, &dll)) {
   3259         Py_DECREF(ftuple);
   3260         return NULL;
   3261     }
   3262 
   3263     obj = PyObject_GetAttrString(dll, "_handle");
   3264     if (!obj) {
   3265         Py_DECREF(ftuple);
   3266         return NULL;
   3267     }
   3268     if (!PyLong_Check(obj)) {
   3269         PyErr_SetString(PyExc_TypeError,
   3270                         "the _handle attribute of the second argument must be an integer");
   3271         Py_DECREF(ftuple);
   3272         Py_DECREF(obj);
   3273         return NULL;
   3274     }
   3275     handle = (void *)PyLong_AsVoidPtr(obj);
   3276     Py_DECREF(obj);
   3277     if (PyErr_Occurred()) {
   3278         PyErr_SetString(PyExc_ValueError,
   3279                         "could not convert the _handle attribute to a pointer");
   3280         Py_DECREF(ftuple);
   3281         return NULL;
   3282     }
   3283 
   3284 #ifdef MS_WIN32
   3285     address = FindAddress(handle, name, (PyObject *)type);
   3286     if (!address) {
   3287         if (!IS_INTRESOURCE(name))
   3288             PyErr_Format(PyExc_AttributeError,
   3289                          "function '%s' not found",
   3290                          name);
   3291         else
   3292             PyErr_Format(PyExc_AttributeError,
   3293                          "function ordinal %d not found",
   3294                          (WORD)(size_t)name);
   3295         Py_DECREF(ftuple);
   3296         return NULL;
   3297     }
   3298 #else
   3299     address = (PPROC)ctypes_dlsym(handle, name);
   3300     if (!address) {
   3301 #ifdef __CYGWIN__
   3302 /* dlerror() isn't very helpful on cygwin */
   3303         PyErr_Format(PyExc_AttributeError,
   3304                      "function '%s' not found",
   3305                      name);
   3306 #else
   3307         PyErr_SetString(PyExc_AttributeError, ctypes_dlerror());
   3308 #endif
   3309         Py_DECREF(ftuple);
   3310         return NULL;
   3311     }
   3312 #endif
   3313     Py_INCREF(dll); /* for KeepRef */
   3314     Py_DECREF(ftuple);
   3315     if (!_validate_paramflags(type, paramflags))
   3316         return NULL;
   3317 
   3318     self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
   3319     if (!self)
   3320         return NULL;
   3321 
   3322     Py_XINCREF(paramflags);
   3323     self->paramflags = paramflags;
   3324 
   3325     *(void **)self->b_ptr = address;
   3326 
   3327     if (-1 == KeepRef((CDataObject *)self, 0, dll)) {
   3328         Py_DECREF((PyObject *)self);
   3329         return NULL;
   3330     }
   3331 
   3332     Py_INCREF(self);
   3333     self->callable = (PyObject *)self;
   3334     return (PyObject *)self;
   3335 }
   3336 
   3337 #ifdef MS_WIN32
   3338 static PyObject *
   3339 PyCFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds)
   3340 {
   3341     PyCFuncPtrObject *self;
   3342     int index;
   3343     char *name = NULL;
   3344     PyObject *paramflags = NULL;
   3345     GUID *iid = NULL;
   3346     Py_ssize_t iid_len = 0;
   3347 
   3348     if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, &paramflags, &iid, &iid_len))
   3349         return NULL;
   3350     if (paramflags == Py_None)
   3351         paramflags = NULL;
   3352 
   3353     if (!_validate_paramflags(type, paramflags))
   3354         return NULL;
   3355 
   3356     self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
   3357     self->index = index + 0x1000;
   3358     Py_XINCREF(paramflags);
   3359     self->paramflags = paramflags;
   3360     if (iid_len == sizeof(GUID))
   3361         self->iid = iid;
   3362     return (PyObject *)self;
   3363 }
   3364 #endif
   3365 
   3366 /*
   3367   PyCFuncPtr_new accepts different argument lists in addition to the standard
   3368   _basespec_ keyword arg:
   3369 
   3370   one argument form
   3371   "i" - function address
   3372   "O" - must be a callable, creates a C callable function
   3373 
   3374   two or more argument forms (the third argument is a paramflags tuple)
   3375   "(sO)|..." - (function name, dll object (with an integer handle)), paramflags
   3376   "(iO)|..." - (function ordinal, dll object (with an integer handle)), paramflags
   3377   "is|..." - vtable index, method name, creates callable calling COM vtbl
   3378 */
   3379 static PyObject *
   3380 PyCFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
   3381 {
   3382     PyCFuncPtrObject *self;
   3383     PyObject *callable;
   3384     StgDictObject *dict;
   3385     CThunkObject *thunk;
   3386 
   3387     if (PyTuple_GET_SIZE(args) == 0)
   3388         return GenericPyCData_new(type, args, kwds);
   3389 
   3390     if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0)))
   3391         return PyCFuncPtr_FromDll(type, args, kwds);
   3392 
   3393 #ifdef MS_WIN32
   3394     if (2 <= PyTuple_GET_SIZE(args) && PyLong_Check(PyTuple_GET_ITEM(args, 0)))
   3395         return PyCFuncPtr_FromVtblIndex(type, args, kwds);
   3396 #endif
   3397 
   3398     if (1 == PyTuple_GET_SIZE(args)
   3399         && (PyLong_Check(PyTuple_GET_ITEM(args, 0)))) {
   3400         CDataObject *ob;
   3401         void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0));
   3402         if (ptr == NULL && PyErr_Occurred())
   3403             return NULL;
   3404         ob = (CDataObject *)GenericPyCData_new(type, args, kwds);
   3405         if (ob == NULL)
   3406             return NULL;
   3407         *(void **)ob->b_ptr = ptr;
   3408         return (PyObject *)ob;
   3409     }
   3410 
   3411     if (!PyArg_ParseTuple(args, "O", &callable))
   3412         return NULL;
   3413     if (!PyCallable_Check(callable)) {
   3414         PyErr_SetString(PyExc_TypeError,
   3415                         "argument must be callable or integer function address");
   3416         return NULL;
   3417     }
   3418 
   3419     /* XXX XXX This would allow passing additional options.  For COM
   3420        method *implementations*, we would probably want different
   3421        behaviour than in 'normal' callback functions: return a HRESULT if
   3422        an exception occurs in the callback, and print the traceback not
   3423        only on the console, but also to OutputDebugString() or something
   3424        like that.
   3425     */
   3426 /*
   3427     if (kwds && PyDict_GetItemString(kwds, "options")) {
   3428         ...
   3429     }
   3430 */
   3431 
   3432     dict = PyType_stgdict((PyObject *)type);
   3433     /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */
   3434     if (!dict || !dict->argtypes) {
   3435         PyErr_SetString(PyExc_TypeError,
   3436                "cannot construct instance of this class:"
   3437             " no argtypes");
   3438         return NULL;
   3439     }
   3440 
   3441     thunk = _ctypes_alloc_callback(callable,
   3442                                   dict->argtypes,
   3443                                   dict->restype,
   3444                                   dict->flags);
   3445     if (!thunk)
   3446         return NULL;
   3447 
   3448     self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
   3449     if (self == NULL) {
   3450         Py_DECREF(thunk);
   3451         return NULL;
   3452     }
   3453 
   3454     Py_INCREF(callable);
   3455     self->callable = callable;
   3456 
   3457     self->thunk = thunk;
   3458     *(void **)self->b_ptr = (void *)thunk->pcl_exec;
   3459 
   3460     Py_INCREF((PyObject *)thunk); /* for KeepRef */
   3461     if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) {
   3462         Py_DECREF((PyObject *)self);
   3463         return NULL;
   3464     }
   3465     return (PyObject *)self;
   3466 }
   3467 
   3468 
   3469 /*
   3470   _byref consumes a refcount to its argument
   3471 */
   3472 static PyObject *
   3473 _byref(PyObject *obj)
   3474 {
   3475     PyCArgObject *parg;
   3476     if (!CDataObject_Check(obj)) {
   3477         PyErr_SetString(PyExc_TypeError,
   3478                         "expected CData instance");
   3479         return NULL;
   3480     }
   3481 
   3482     parg = PyCArgObject_new();
   3483     if (parg == NULL) {
   3484         Py_DECREF(obj);
   3485         return NULL;
   3486     }
   3487 
   3488     parg->tag = 'P';
   3489     parg->pffi_type = &ffi_type_pointer;
   3490     parg->obj = obj;
   3491     parg->value.p = ((CDataObject *)obj)->b_ptr;
   3492     return (PyObject *)parg;
   3493 }
   3494 
   3495 static PyObject *
   3496 _get_arg(int *pindex, PyObject *name, PyObject *defval, PyObject *inargs, PyObject *kwds)
   3497 {
   3498     PyObject *v;
   3499 
   3500     if (*pindex < PyTuple_GET_SIZE(inargs)) {
   3501         v = PyTuple_GET_ITEM(inargs, *pindex);
   3502         ++*pindex;
   3503         Py_INCREF(v);
   3504         return v;
   3505     }
   3506     if (kwds && name && (v = PyDict_GetItem(kwds, name))) {
   3507         ++*pindex;
   3508         Py_INCREF(v);
   3509         return v;
   3510     }
   3511     if (defval) {
   3512         Py_INCREF(defval);
   3513         return defval;
   3514     }
   3515     /* we can't currently emit a better error message */
   3516     if (name)
   3517         PyErr_Format(PyExc_TypeError,
   3518                      "required argument '%S' missing", name);
   3519     else
   3520         PyErr_Format(PyExc_TypeError,
   3521                      "not enough arguments");
   3522     return NULL;
   3523 }
   3524 
   3525 /*
   3526  This function implements higher level functionality plus the ability to call
   3527  functions with keyword arguments by looking at parameter flags.  parameter
   3528  flags is a tuple of 1, 2 or 3-tuples.  The first entry in each is an integer
   3529  specifying the direction of the data transfer for this parameter - 'in',
   3530  'out' or 'inout' (zero means the same as 'in').  The second entry is the
   3531  parameter name, and the third is the default value if the parameter is
   3532  missing in the function call.
   3533 
   3534  This function builds and returns a new tuple 'callargs' which contains the
   3535  parameters to use in the call.  Items on this tuple are copied from the
   3536  'inargs' tuple for 'in' and 'in, out' parameters, and constructed from the
   3537  'argtypes' tuple for 'out' parameters.  It also calculates numretvals which
   3538  is the number of return values for the function, outmask/inoutmask are
   3539  bitmasks containing indexes into the callargs tuple specifying which
   3540  parameters have to be returned.  _build_result builds the return value of the
   3541  function.
   3542 */
   3543 static PyObject *
   3544 _build_callargs(PyCFuncPtrObject *self, PyObject *argtypes,
   3545                 PyObject *inargs, PyObject *kwds,
   3546                 int *poutmask, int *pinoutmask, unsigned int *pnumretvals)
   3547 {
   3548     PyObject *paramflags = self->paramflags;
   3549     PyObject *callargs;
   3550     StgDictObject *dict;
   3551     Py_ssize_t i, len;
   3552     int inargs_index = 0;
   3553     /* It's a little bit difficult to determine how many arguments the
   3554     function call requires/accepts.  For simplicity, we count the consumed
   3555     args and compare this to the number of supplied args. */
   3556     Py_ssize_t actual_args;
   3557 
   3558     *poutmask = 0;
   3559     *pinoutmask = 0;
   3560     *pnumretvals = 0;
   3561 
   3562     /* Trivial cases, where we either return inargs itself, or a slice of it. */
   3563     if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) {
   3564 #ifdef MS_WIN32
   3565         if (self->index)
   3566             return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs));
   3567 #endif
   3568         Py_INCREF(inargs);
   3569         return inargs;
   3570     }
   3571 
   3572     len = PyTuple_GET_SIZE(argtypes);
   3573     callargs = PyTuple_New(len); /* the argument tuple we build */
   3574     if (callargs == NULL)
   3575         return NULL;
   3576 
   3577 #ifdef MS_WIN32
   3578     /* For a COM method, skip the first arg */
   3579     if (self->index) {
   3580         inargs_index = 1;
   3581     }
   3582 #endif
   3583     for (i = 0; i < len; ++i) {
   3584         PyObject *item = PyTuple_GET_ITEM(paramflags, i);
   3585         PyObject *ob;
   3586         int flag;
   3587         PyObject *name = NULL;
   3588         PyObject *defval = NULL;
   3589 
   3590         /* This way seems to be ~2 us faster than the PyArg_ParseTuple
   3591            calls below. */
   3592         /* We HAVE already checked that the tuple can be parsed with "i|ZO", so... */
   3593         Py_ssize_t tsize = PyTuple_GET_SIZE(item);
   3594         flag = PyLong_AS_LONG(PyTuple_GET_ITEM(item, 0));
   3595         name = tsize > 1 ? PyTuple_GET_ITEM(item, 1) : NULL;
   3596         defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL;
   3597 
   3598         switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
   3599         case PARAMFLAG_FIN | PARAMFLAG_FLCID:
   3600             /* ['in', 'lcid'] parameter.  Always taken from defval,
   3601              if given, else the integer 0. */
   3602             if (defval == NULL) {
   3603                 defval = PyLong_FromLong(0);
   3604                 if (defval == NULL)
   3605                     goto error;
   3606             } else
   3607                 Py_INCREF(defval);
   3608             PyTuple_SET_ITEM(callargs, i, defval);
   3609             break;
   3610         case (PARAMFLAG_FIN | PARAMFLAG_FOUT):
   3611             *pinoutmask |= (1 << i); /* mark as inout arg */
   3612             (*pnumretvals)++;
   3613             /* fall through to PARAMFLAG_FIN... */
   3614         case 0:
   3615         case PARAMFLAG_FIN:
   3616             /* 'in' parameter.  Copy it from inargs. */
   3617             ob =_get_arg(&inargs_index, name, defval, inargs, kwds);
   3618             if (ob == NULL)
   3619                 goto error;
   3620             PyTuple_SET_ITEM(callargs, i, ob);
   3621             break;
   3622         case PARAMFLAG_FOUT:
   3623             /* XXX Refactor this code into a separate function. */
   3624             /* 'out' parameter.
   3625                argtypes[i] must be a POINTER to a c type.
   3626 
   3627                Cannot by supplied in inargs, but a defval will be used
   3628                if available.  XXX Should we support getting it from kwds?
   3629             */
   3630             if (defval) {
   3631                 /* XXX Using mutable objects as defval will
   3632                    make the function non-threadsafe, unless we
   3633                    copy the object in each invocation */
   3634                 Py_INCREF(defval);
   3635                 PyTuple_SET_ITEM(callargs, i, defval);
   3636                 *poutmask |= (1 << i); /* mark as out arg */
   3637                 (*pnumretvals)++;
   3638                 break;
   3639             }
   3640             ob = PyTuple_GET_ITEM(argtypes, i);
   3641             dict = PyType_stgdict(ob);
   3642             if (dict == NULL) {
   3643                 /* Cannot happen: _validate_paramflags()
   3644                   would not accept such an object */
   3645                 PyErr_Format(PyExc_RuntimeError,
   3646                              "NULL stgdict unexpected");
   3647                 goto error;
   3648             }
   3649             if (PyUnicode_Check(dict->proto)) {
   3650                 PyErr_Format(
   3651                     PyExc_TypeError,
   3652                     "%s 'out' parameter must be passed as default value",
   3653                     ((PyTypeObject *)ob)->tp_name);
   3654                 goto error;
   3655             }
   3656             if (PyCArrayTypeObject_Check(ob))
   3657                 ob = PyObject_CallObject(ob, NULL);
   3658             else
   3659                 /* Create an instance of the pointed-to type */
   3660                 ob = PyObject_CallObject(dict->proto, NULL);
   3661             /*
   3662                XXX Is the following correct any longer?
   3663                We must not pass a byref() to the array then but
   3664                the array instance itself. Then, we cannot retrive
   3665                the result from the PyCArgObject.
   3666             */
   3667             if (ob == NULL)
   3668                 goto error;
   3669             /* The .from_param call that will ocurr later will pass this
   3670                as a byref parameter. */
   3671             PyTuple_SET_ITEM(callargs, i, ob);
   3672             *poutmask |= (1 << i); /* mark as out arg */
   3673             (*pnumretvals)++;
   3674             break;
   3675         default:
   3676             PyErr_Format(PyExc_ValueError,
   3677                          "paramflag %d not yet implemented", flag);
   3678             goto error;
   3679             break;
   3680         }
   3681     }
   3682 
   3683     /* We have counted the arguments we have consumed in 'inargs_index'.  This
   3684        must be the same as len(inargs) + len(kwds), otherwise we have
   3685        either too much or not enough arguments. */
   3686 
   3687     actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_Size(kwds) : 0);
   3688     if (actual_args != inargs_index) {
   3689         /* When we have default values or named parameters, this error
   3690            message is misleading.  See unittests/test_paramflags.py
   3691          */
   3692         PyErr_Format(PyExc_TypeError,
   3693                      "call takes exactly %d arguments (%zd given)",
   3694                      inargs_index, actual_args);
   3695         goto error;
   3696     }
   3697 
   3698     /* outmask is a bitmask containing indexes into callargs.  Items at
   3699        these indexes contain values to return.
   3700      */
   3701     return callargs;
   3702   error:
   3703     Py_DECREF(callargs);
   3704     return NULL;
   3705 }
   3706 
   3707 /* See also:
   3708    http://msdn.microsoft.com/library/en-us/com/html/769127a1-1a14-4ed4-9d38-7cf3e571b661.asp
   3709 */
   3710 /*
   3711   Build return value of a function.
   3712 
   3713   Consumes the refcount on result and callargs.
   3714 */
   3715 static PyObject *
   3716 _build_result(PyObject *result, PyObject *callargs,
   3717               int outmask, int inoutmask, unsigned int numretvals)
   3718 {
   3719     unsigned int i, index;
   3720     int bit;
   3721     PyObject *tup = NULL;
   3722 
   3723     if (callargs == NULL)
   3724         return result;
   3725     if (result == NULL || numretvals == 0) {
   3726         Py_DECREF(callargs);
   3727         return result;
   3728     }
   3729     Py_DECREF(result);
   3730 
   3731     /* tup will not be allocated if numretvals == 1 */
   3732     /* allocate tuple to hold the result */
   3733     if (numretvals > 1) {
   3734         tup = PyTuple_New(numretvals);
   3735         if (tup == NULL) {
   3736             Py_DECREF(callargs);
   3737             return NULL;
   3738         }
   3739     }
   3740 
   3741     index = 0;
   3742     for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) {
   3743         PyObject *v;
   3744         if (bit & inoutmask) {
   3745             v = PyTuple_GET_ITEM(callargs, i);
   3746             Py_INCREF(v);
   3747             if (numretvals == 1) {
   3748                 Py_DECREF(callargs);
   3749                 return v;
   3750             }
   3751             PyTuple_SET_ITEM(tup, index, v);
   3752             index++;
   3753         } else if (bit & outmask) {
   3754             _Py_IDENTIFIER(__ctypes_from_outparam__);
   3755 
   3756             v = PyTuple_GET_ITEM(callargs, i);
   3757             v = _PyObject_CallMethodId(v, &PyId___ctypes_from_outparam__, NULL);
   3758             if (v == NULL || numretvals == 1) {
   3759                 Py_DECREF(callargs);
   3760                 return v;
   3761             }
   3762             PyTuple_SET_ITEM(tup, index, v);
   3763             index++;
   3764         }
   3765         if (index == numretvals)
   3766             break;
   3767     }
   3768 
   3769     Py_DECREF(callargs);
   3770     return tup;
   3771 }
   3772 
   3773 static PyObject *
   3774 PyCFuncPtr_call(PyCFuncPtrObject *self, PyObject *inargs, PyObject *kwds)
   3775 {
   3776     PyObject *restype;
   3777     PyObject *converters;
   3778     PyObject *checker;
   3779     PyObject *argtypes;
   3780     StgDictObject *dict = PyObject_stgdict((PyObject *)self);
   3781     PyObject *result;
   3782     PyObject *callargs;
   3783     PyObject *errcheck;
   3784 #ifdef MS_WIN32
   3785     IUnknown *piunk = NULL;
   3786 #endif
   3787     void *pProc = NULL;
   3788 
   3789     int inoutmask;
   3790     int outmask;
   3791     unsigned int numretvals;
   3792 
   3793     assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
   3794     restype = self->restype ? self->restype : dict->restype;
   3795     converters = self->converters ? self->converters : dict->converters;
   3796     checker = self->checker ? self->checker : dict->checker;
   3797     argtypes = self->argtypes ? self->argtypes : dict->argtypes;
   3798 /* later, we probably want to have an errcheck field in stgdict */
   3799     errcheck = self->errcheck /* ? self->errcheck : dict->errcheck */;
   3800 
   3801 
   3802     pProc = *(void **)self->b_ptr;
   3803 #ifdef MS_WIN32
   3804     if (self->index) {
   3805         /* It's a COM method */
   3806         CDataObject *this;
   3807         this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */
   3808         if (!this) {
   3809             PyErr_SetString(PyExc_ValueError,
   3810                             "native com method call without 'this' parameter");
   3811             return NULL;
   3812         }
   3813         if (!CDataObject_Check(this)) {
   3814             PyErr_SetString(PyExc_TypeError,
   3815                             "Expected a COM this pointer as first argument");
   3816             return NULL;
   3817         }
   3818         /* there should be more checks? No, in Python */
   3819         /* First arg is a pointer to an interface instance */
   3820         if (!this->b_ptr || *(void **)this->b_ptr == NULL) {
   3821             PyErr_SetString(PyExc_ValueError,
   3822                             "NULL COM pointer access");
   3823             return NULL;
   3824         }
   3825         piunk = *(IUnknown **)this->b_ptr;
   3826         if (NULL == piunk->lpVtbl) {
   3827             PyErr_SetString(PyExc_ValueError,
   3828                             "COM method call without VTable");
   3829             return NULL;
   3830         }
   3831         pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000];
   3832     }
   3833 #endif
   3834     callargs = _build_callargs(self, argtypes,
   3835                                inargs, kwds,
   3836                                &outmask, &inoutmask, &numretvals);
   3837     if (callargs == NULL)
   3838         return NULL;
   3839 
   3840     if (converters) {
   3841         int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters),
   3842                                         Py_ssize_t, int);
   3843         int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs),
   3844                                       Py_ssize_t, int);
   3845 
   3846         if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) {
   3847             /* For cdecl functions, we allow more actual arguments
   3848                than the length of the argtypes tuple.
   3849             */
   3850             if (required > actual) {
   3851                 Py_DECREF(callargs);
   3852                 PyErr_Format(PyExc_TypeError,
   3853               "this function takes at least %d argument%s (%d given)",
   3854                                  required,
   3855                                  required == 1 ? "" : "s",
   3856                                  actual);
   3857                 return NULL;
   3858             }
   3859         } else if (required != actual) {
   3860             Py_DECREF(callargs);
   3861             PyErr_Format(PyExc_TypeError,
   3862                  "this function takes %d argument%s (%d given)",
   3863                      required,
   3864                      required == 1 ? "" : "s",
   3865                      actual);
   3866             return NULL;
   3867         }
   3868     }
   3869 
   3870     result = _ctypes_callproc(pProc,
   3871                        callargs,
   3872 #ifdef MS_WIN32
   3873                        piunk,
   3874                        self->iid,
   3875 #endif
   3876                        dict->flags,
   3877                        converters,
   3878                        restype,
   3879                        checker);
   3880 /* The 'errcheck' protocol */
   3881     if (result != NULL && errcheck) {
   3882         PyObject *v = PyObject_CallFunctionObjArgs(errcheck,
   3883                                                    result,
   3884                                                    self,
   3885                                                    callargs,
   3886                                                    NULL);
   3887         /* If the errcheck function failed, return NULL.
   3888            If the errcheck function returned callargs unchanged,
   3889            continue normal processing.
   3890            If the errcheck function returned something else,
   3891            use that as result.
   3892         */
   3893         if (v == NULL || v != callargs) {
   3894             Py_DECREF(result);
   3895             Py_DECREF(callargs);
   3896             return v;
   3897         }
   3898         Py_DECREF(v);
   3899     }
   3900 
   3901     return _build_result(result, callargs,
   3902                          outmask, inoutmask, numretvals);
   3903 }
   3904 
   3905 static int
   3906 PyCFuncPtr_traverse(PyCFuncPtrObject *self, visitproc visit, void *arg)
   3907 {
   3908     Py_VISIT(self->callable);
   3909     Py_VISIT(self->restype);
   3910     Py_VISIT(self->checker);
   3911     Py_VISIT(self->errcheck);
   3912     Py_VISIT(self->argtypes);
   3913     Py_VISIT(self->converters);
   3914     Py_VISIT(self->paramflags);
   3915     Py_VISIT(self->thunk);
   3916     return PyCData_traverse((CDataObject *)self, visit, arg);
   3917 }
   3918 
   3919 static int
   3920 PyCFuncPtr_clear(PyCFuncPtrObject *self)
   3921 {
   3922     Py_CLEAR(self->callable);
   3923     Py_CLEAR(self->restype);
   3924     Py_CLEAR(self->checker);
   3925     Py_CLEAR(self->errcheck);
   3926     Py_CLEAR(self->argtypes);
   3927     Py_CLEAR(self->converters);
   3928     Py_CLEAR(self->paramflags);
   3929     Py_CLEAR(self->thunk);
   3930     return PyCData_clear((CDataObject *)self);
   3931 }
   3932 
   3933 static void
   3934 PyCFuncPtr_dealloc(PyCFuncPtrObject *self)
   3935 {
   3936     PyCFuncPtr_clear(self);
   3937     Py_TYPE(self)->tp_free((PyObject *)self);
   3938 }
   3939 
   3940 static PyObject *
   3941 PyCFuncPtr_repr(PyCFuncPtrObject *self)
   3942 {
   3943 #ifdef MS_WIN32
   3944     if (self->index)
   3945         return PyUnicode_FromFormat("<COM method offset %d: %s at %p>",
   3946                                    self->index - 0x1000,
   3947                                    Py_TYPE(self)->tp_name,
   3948                                    self);
   3949 #endif
   3950     return PyUnicode_FromFormat("<%s object at %p>",
   3951                                Py_TYPE(self)->tp_name,
   3952                                self);
   3953 }
   3954 
   3955 static int
   3956 PyCFuncPtr_bool(PyCFuncPtrObject *self)
   3957 {
   3958     return ((*(void **)self->b_ptr != NULL)
   3959 #ifdef MS_WIN32
   3960         || (self->index != 0)
   3961 #endif
   3962         );
   3963 }
   3964 
   3965 static PyNumberMethods PyCFuncPtr_as_number = {
   3966     0, /* nb_add */
   3967     0, /* nb_subtract */
   3968     0, /* nb_multiply */
   3969     0, /* nb_remainder */
   3970     0, /* nb_divmod */
   3971     0, /* nb_power */
   3972     0, /* nb_negative */
   3973     0, /* nb_positive */
   3974     0, /* nb_absolute */
   3975     (inquiry)PyCFuncPtr_bool, /* nb_bool */
   3976 };
   3977 
   3978 PyTypeObject PyCFuncPtr_Type = {
   3979     PyVarObject_HEAD_INIT(NULL, 0)
   3980     "_ctypes.PyCFuncPtr",
   3981     sizeof(PyCFuncPtrObject),                           /* tp_basicsize */
   3982     0,                                          /* tp_itemsize */
   3983     (destructor)PyCFuncPtr_dealloc,             /* tp_dealloc */
   3984     0,                                          /* tp_print */
   3985     0,                                          /* tp_getattr */
   3986     0,                                          /* tp_setattr */
   3987     0,                                          /* tp_reserved */
   3988     (reprfunc)PyCFuncPtr_repr,                  /* tp_repr */
   3989     &PyCFuncPtr_as_number,                      /* tp_as_number */
   3990     0,                                          /* tp_as_sequence */
   3991     0,                                          /* tp_as_mapping */
   3992     0,                                          /* tp_hash */
   3993     (ternaryfunc)PyCFuncPtr_call,               /* tp_call */
   3994     0,                                          /* tp_str */
   3995     0,                                          /* tp_getattro */
   3996     0,                                          /* tp_setattro */
   3997     &PyCData_as_buffer,                         /* tp_as_buffer */
   3998     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
   3999     "Function Pointer",                         /* tp_doc */
   4000     (traverseproc)PyCFuncPtr_traverse,          /* tp_traverse */
   4001     (inquiry)PyCFuncPtr_clear,                  /* tp_clear */
   4002     0,                                          /* tp_richcompare */
   4003     0,                                          /* tp_weaklistoffset */
   4004     0,                                          /* tp_iter */
   4005     0,                                          /* tp_iternext */
   4006     0,                                          /* tp_methods */
   4007     0,                                          /* tp_members */
   4008     PyCFuncPtr_getsets,                         /* tp_getset */
   4009     0,                                          /* tp_base */
   4010     0,                                          /* tp_dict */
   4011     0,                                          /* tp_descr_get */
   4012     0,                                          /* tp_descr_set */
   4013     0,                                          /* tp_dictoffset */
   4014     0,                                          /* tp_init */
   4015     0,                                          /* tp_alloc */
   4016     PyCFuncPtr_new,                             /* tp_new */
   4017     0,                                          /* tp_free */
   4018 };
   4019 
   4020 /*****************************************************************/
   4021 /*
   4022   Struct_Type
   4023 */
   4024 /*
   4025   This function is called to initialize a Structure or Union with positional
   4026   arguments. It calls itself recursively for all Structure or Union base
   4027   classes, then retrieves the _fields_ member to associate the argument
   4028   position with the correct field name.
   4029 
   4030   Returns -1 on error, or the index of next argument on success.
   4031  */
   4032 static Py_ssize_t
   4033 _init_pos_args(PyObject *self, PyTypeObject *type,
   4034                PyObject *args, PyObject *kwds,
   4035                Py_ssize_t index)
   4036 {
   4037     StgDictObject *dict;
   4038     PyObject *fields;
   4039     Py_ssize_t i;
   4040 
   4041     if (PyType_stgdict((PyObject *)type->tp_base)) {
   4042         index = _init_pos_args(self, type->tp_base,
   4043                                args, kwds,
   4044                                index);
   4045         if (index == -1)
   4046             return -1;
   4047     }
   4048 
   4049     dict = PyType_stgdict((PyObject *)type);
   4050     fields = PyDict_GetItemString((PyObject *)dict, "_fields_");
   4051     if (fields == NULL)
   4052         return index;
   4053 
   4054     for (i = 0;
   4055          i < dict->length && (i+index) < PyTuple_GET_SIZE(args);
   4056          ++i) {
   4057         PyObject *pair = PySequence_GetItem(fields, i);
   4058         PyObject *name, *val;
   4059         int res;
   4060         if (!pair)
   4061             return -1;
   4062         name = PySequence_GetItem(pair, 0);
   4063         if (!name) {
   4064             Py_DECREF(pair);
   4065             return -1;
   4066         }
   4067         val = PyTuple_GET_ITEM(args, i + index);
   4068         if (kwds && PyDict_GetItem(kwds, name)) {
   4069             PyErr_Format(PyExc_TypeError,
   4070                          "duplicate values for field %R",
   4071                          name);
   4072             Py_DECREF(pair);
   4073             Py_DECREF(name);
   4074             return -1;
   4075         }
   4076 
   4077         res = PyObject_SetAttr(self, name, val);
   4078         Py_DECREF(pair);
   4079         Py_DECREF(name);
   4080         if (res == -1)
   4081             return -1;
   4082     }
   4083     return index + dict->length;
   4084 }
   4085 
   4086 static int
   4087 Struct_init(PyObject *self, PyObject *args, PyObject *kwds)
   4088 {
   4089 /* Optimization possible: Store the attribute names _fields_[x][0]
   4090  * in C accessible fields somewhere ?
   4091  */
   4092     if (!PyTuple_Check(args)) {
   4093         PyErr_SetString(PyExc_TypeError,
   4094                         "args not a tuple?");
   4095         return -1;
   4096     }
   4097     if (PyTuple_GET_SIZE(args)) {
   4098         Py_ssize_t res = _init_pos_args(self, Py_TYPE(self),
   4099                                         args, kwds, 0);
   4100         if (res == -1)
   4101             return -1;
   4102         if (res < PyTuple_GET_SIZE(args)) {
   4103             PyErr_SetString(PyExc_TypeError,
   4104                             "too many initializers");
   4105             return -1;
   4106         }
   4107     }
   4108 
   4109     if (kwds) {
   4110         PyObject *key, *value;
   4111         Py_ssize_t pos = 0;
   4112         while(PyDict_Next(kwds, &pos, &key, &value)) {
   4113             if (-1 == PyObject_SetAttr(self, key, value))
   4114                 return -1;
   4115         }
   4116     }
   4117     return 0;
   4118 }
   4119 
   4120 static PyTypeObject Struct_Type = {
   4121     PyVarObject_HEAD_INIT(NULL, 0)
   4122     "_ctypes.Structure",
   4123     sizeof(CDataObject),                        /* tp_basicsize */
   4124     0,                                          /* tp_itemsize */
   4125     0,                                          /* tp_dealloc */
   4126     0,                                          /* tp_print */
   4127     0,                                          /* tp_getattr */
   4128     0,                                          /* tp_setattr */
   4129     0,                                          /* tp_reserved */
   4130     0,                                          /* tp_repr */
   4131     0,                                          /* tp_as_number */
   4132     0,                                          /* tp_as_sequence */
   4133     0,                                          /* tp_as_mapping */
   4134     0,                                          /* tp_hash */
   4135     0,                                          /* tp_call */
   4136     0,                                          /* tp_str */
   4137     0,                                          /* tp_getattro */
   4138     0,                                          /* tp_setattro */
   4139     &PyCData_as_buffer,                         /* tp_as_buffer */
   4140     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
   4141     "Structure base class",                     /* tp_doc */
   4142     (traverseproc)PyCData_traverse,             /* tp_traverse */
   4143     (inquiry)PyCData_clear,                     /* tp_clear */
   4144     0,                                          /* tp_richcompare */
   4145     0,                                          /* tp_weaklistoffset */
   4146     0,                                          /* tp_iter */
   4147     0,                                          /* tp_iternext */
   4148     0,                                          /* tp_methods */
   4149     0,                                          /* tp_members */
   4150     0,                                          /* tp_getset */
   4151     0,                                          /* tp_base */
   4152     0,                                          /* tp_dict */
   4153     0,                                          /* tp_descr_get */
   4154     0,                                          /* tp_descr_set */
   4155     0,                                          /* tp_dictoffset */
   4156     Struct_init,                                /* tp_init */
   4157     0,                                          /* tp_alloc */
   4158     GenericPyCData_new,                         /* tp_new */
   4159     0,                                          /* tp_free */
   4160 };
   4161 
   4162 static PyTypeObject Union_Type = {
   4163     PyVarObject_HEAD_INIT(NULL, 0)
   4164     "_ctypes.Union",
   4165     sizeof(CDataObject),                        /* tp_basicsize */
   4166     0,                                          /* tp_itemsize */
   4167     0,                                          /* tp_dealloc */
   4168     0,                                          /* tp_print */
   4169     0,                                          /* tp_getattr */
   4170     0,                                          /* tp_setattr */
   4171     0,                                          /* tp_reserved */
   4172     0,                                          /* tp_repr */
   4173     0,                                          /* tp_as_number */
   4174     0,                                          /* tp_as_sequence */
   4175     0,                                          /* tp_as_mapping */
   4176     0,                                          /* tp_hash */
   4177     0,                                          /* tp_call */
   4178     0,                                          /* tp_str */
   4179     0,                                          /* tp_getattro */
   4180     0,                                          /* tp_setattro */
   4181     &PyCData_as_buffer,                         /* tp_as_buffer */
   4182     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
   4183     "Union base class",                         /* tp_doc */
   4184     (traverseproc)PyCData_traverse,             /* tp_traverse */
   4185     (inquiry)PyCData_clear,                     /* tp_clear */
   4186     0,                                          /* tp_richcompare */
   4187     0,                                          /* tp_weaklistoffset */
   4188     0,                                          /* tp_iter */
   4189     0,                                          /* tp_iternext */
   4190     0,                                          /* tp_methods */
   4191     0,                                          /* tp_members */
   4192     0,                                          /* tp_getset */
   4193     0,                                          /* tp_base */
   4194     0,                                          /* tp_dict */
   4195     0,                                          /* tp_descr_get */
   4196     0,                                          /* tp_descr_set */
   4197     0,                                          /* tp_dictoffset */
   4198     Struct_init,                                /* tp_init */
   4199     0,                                          /* tp_alloc */
   4200     GenericPyCData_new,                         /* tp_new */
   4201     0,                                          /* tp_free */
   4202 };
   4203 
   4204 
   4205 /******************************************************************/
   4206 /*
   4207   PyCArray_Type
   4208 */
   4209 static int
   4210 Array_init(CDataObject *self, PyObject *args, PyObject *kw)
   4211 {
   4212     Py_ssize_t i;
   4213     Py_ssize_t n;
   4214 
   4215     if (!PyTuple_Check(args)) {
   4216         PyErr_SetString(PyExc_TypeError,
   4217                         "args not a tuple?");
   4218         return -1;
   4219     }
   4220     n = PyTuple_GET_SIZE(args);
   4221     for (i = 0; i < n; ++i) {
   4222         PyObject *v;
   4223         v = PyTuple_GET_ITEM(args, i);
   4224         if (-1 == PySequence_SetItem((PyObject *)self, i, v))
   4225             return -1;
   4226     }
   4227     return 0;
   4228 }
   4229 
   4230 static PyObject *
   4231 Array_item(PyObject *myself, Py_ssize_t index)
   4232 {
   4233     CDataObject *self = (CDataObject *)myself;
   4234     Py_ssize_t offset, size;
   4235     StgDictObject *stgdict;
   4236 
   4237 
   4238     if (index < 0 || index >= self->b_length) {
   4239         PyErr_SetString(PyExc_IndexError,
   4240                         "invalid index");
   4241         return NULL;
   4242     }
   4243 
   4244     stgdict = PyObject_stgdict((PyObject *)self);
   4245     assert(stgdict); /* Cannot be NULL for array instances */
   4246     /* Would it be clearer if we got the item size from
   4247        stgdict->proto's stgdict?
   4248     */
   4249     size = stgdict->size / stgdict->length;
   4250     offset = index * size;
   4251 
   4252     return PyCData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self,
   4253                      index, size, self->b_ptr + offset);
   4254 }
   4255 
   4256 static PyObject *
   4257 Array_subscript(PyObject *myself, PyObject *item)
   4258 {
   4259     CDataObject *self = (CDataObject *)myself;
   4260 
   4261     if (PyIndex_Check(item)) {
   4262         Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
   4263 
   4264         if (i == -1 && PyErr_Occurred())
   4265             return NULL;
   4266         if (i < 0)
   4267             i += self->b_length;
   4268         return Array_item(myself, i);
   4269     }
   4270     else if (PySlice_Check(item)) {
   4271         StgDictObject *stgdict, *itemdict;
   4272         PyObject *proto;
   4273         PyObject *np;
   4274         Py_ssize_t start, stop, step, slicelen, cur, i;
   4275 
   4276         if (PySlice_GetIndicesEx(item,
   4277                                  self->b_length, &start, &stop,
   4278                                  &step, &slicelen) < 0) {
   4279             return NULL;
   4280         }
   4281 
   4282         stgdict = PyObject_stgdict((PyObject *)self);
   4283         assert(stgdict); /* Cannot be NULL for array object instances */
   4284         proto = stgdict->proto;
   4285         itemdict = PyType_stgdict(proto);
   4286         assert(itemdict); /* proto is the item type of the array, a
   4287                              ctypes type, so this cannot be NULL */
   4288 
   4289         if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
   4290             char *ptr = (char *)self->b_ptr;
   4291             char *dest;
   4292 
   4293             if (slicelen <= 0)
   4294                 return PyBytes_FromStringAndSize("", 0);
   4295             if (step == 1) {
   4296                 return PyBytes_FromStringAndSize(ptr + start,
   4297                                                  slicelen);
   4298             }
   4299             dest = (char *)PyMem_Malloc(slicelen);
   4300 
   4301             if (dest == NULL)
   4302                 return PyErr_NoMemory();
   4303 
   4304             for (cur = start, i = 0; i < slicelen;
   4305                  cur += step, i++) {
   4306                 dest[i] = ptr[cur];
   4307             }
   4308 
   4309             np = PyBytes_FromStringAndSize(dest, slicelen);
   4310             PyMem_Free(dest);
   4311             return np;
   4312         }
   4313 #ifdef CTYPES_UNICODE
   4314         if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
   4315             wchar_t *ptr = (wchar_t *)self->b_ptr;
   4316             wchar_t *dest;
   4317 
   4318             if (slicelen <= 0)
   4319                 return PyUnicode_New(0, 0);
   4320             if (step == 1) {
   4321                 return PyUnicode_FromWideChar(ptr + start,
   4322                                               slicelen);
   4323             }
   4324 
   4325             dest = PyMem_New(wchar_t, slicelen);
   4326             if (dest == NULL) {
   4327                 PyErr_NoMemory();
   4328                 return NULL;
   4329             }
   4330 
   4331             for (cur = start, i = 0; i < slicelen;
   4332                  cur += step, i++) {
   4333                 dest[i] = ptr[cur];
   4334             }
   4335 
   4336             np = PyUnicode_FromWideChar(dest, slicelen);
   4337             PyMem_Free(dest);
   4338             return np;
   4339         }
   4340 #endif
   4341 
   4342         np = PyList_New(slicelen);
   4343         if (np == NULL)
   4344             return NULL;
   4345 
   4346         for (cur = start, i = 0; i < slicelen;
   4347              cur += step, i++) {
   4348             PyObject *v = Array_item(myself, cur);
   4349             if (v == NULL) {
   4350                 Py_DECREF(np);
   4351                 return NULL;
   4352             }
   4353             PyList_SET_ITEM(np, i, v);
   4354         }
   4355         return np;
   4356     }
   4357     else {
   4358         PyErr_SetString(PyExc_TypeError,
   4359                         "indices must be integers");
   4360         return NULL;
   4361     }
   4362 
   4363 }
   4364 
   4365 static int
   4366 Array_ass_item(PyObject *myself, Py_ssize_t index, PyObject *value)
   4367 {
   4368     CDataObject *self = (CDataObject *)myself;
   4369     Py_ssize_t size, offset;
   4370     StgDictObject *stgdict;
   4371     char *ptr;
   4372 
   4373     if (value == NULL) {
   4374         PyErr_SetString(PyExc_TypeError,
   4375                         "Array does not support item deletion");
   4376         return -1;
   4377     }
   4378 
   4379     stgdict = PyObject_stgdict((PyObject *)self);
   4380     assert(stgdict); /* Cannot be NULL for array object instances */
   4381     if (index < 0 || index >= stgdict->length) {
   4382         PyErr_SetString(PyExc_IndexError,
   4383                         "invalid index");
   4384         return -1;
   4385     }
   4386     size = stgdict->size / stgdict->length;
   4387     offset = index * size;
   4388     ptr = self->b_ptr + offset;
   4389 
   4390     return PyCData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value,
   4391                      index, size, ptr);
   4392 }
   4393 
   4394 static int
   4395 Array_ass_subscript(PyObject *myself, PyObject *item, PyObject *value)
   4396 {
   4397     CDataObject *self = (CDataObject *)myself;
   4398 
   4399     if (value == NULL) {
   4400         PyErr_SetString(PyExc_TypeError,
   4401                         "Array does not support item deletion");
   4402         return -1;
   4403     }
   4404 
   4405     if (PyIndex_Check(item)) {
   4406         Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
   4407 
   4408         if (i == -1 && PyErr_Occurred())
   4409             return -1;
   4410         if (i < 0)
   4411             i += self->b_length;
   4412         return Array_ass_item(myself, i, value);
   4413     }
   4414     else if (PySlice_Check(item)) {
   4415         Py_ssize_t start, stop, step, slicelen, otherlen, i, cur;
   4416 
   4417         if (PySlice_GetIndicesEx(item,
   4418                                  self->b_length, &start, &stop,
   4419                                  &step, &slicelen) < 0) {
   4420             return -1;
   4421         }
   4422         if ((step < 0 && start < stop) ||
   4423             (step > 0 && start > stop))
   4424             stop = start;
   4425 
   4426         otherlen = PySequence_Length(value);
   4427         if (otherlen != slicelen) {
   4428             PyErr_SetString(PyExc_ValueError,
   4429                 "Can only assign sequence of same size");
   4430             return -1;
   4431         }
   4432         for (cur = start, i = 0; i < otherlen; cur += step, i++) {
   4433             PyObject *item = PySequence_GetItem(value, i);
   4434             int result;
   4435             if (item == NULL)
   4436                 return -1;
   4437             result = Array_ass_item(myself, cur, item);
   4438             Py_DECREF(item);
   4439             if (result == -1)
   4440                 return -1;
   4441         }
   4442         return 0;
   4443     }
   4444     else {
   4445         PyErr_SetString(PyExc_TypeError,
   4446                         "indices must be integer");
   4447         return -1;
   4448     }
   4449 }
   4450 
   4451 static Py_ssize_t
   4452 Array_length(PyObject *myself)
   4453 {
   4454     CDataObject *self = (CDataObject *)myself;
   4455     return self->b_length;
   4456 }
   4457 
   4458 static PySequenceMethods Array_as_sequence = {
   4459     Array_length,                               /* sq_length; */
   4460     0,                                          /* sq_concat; */
   4461     0,                                          /* sq_repeat; */
   4462     Array_item,                                 /* sq_item; */
   4463     0,                                          /* sq_slice; */
   4464     Array_ass_item,                             /* sq_ass_item; */
   4465     0,                                          /* sq_ass_slice; */
   4466     0,                                          /* sq_contains; */
   4467 
   4468     0,                                          /* sq_inplace_concat; */
   4469     0,                                          /* sq_inplace_repeat; */
   4470 };
   4471 
   4472 static PyMappingMethods Array_as_mapping = {
   4473     Array_length,
   4474     Array_subscript,
   4475     Array_ass_subscript,
   4476 };
   4477 
   4478 PyTypeObject PyCArray_Type = {
   4479     PyVarObject_HEAD_INIT(NULL, 0)
   4480     "_ctypes.Array",
   4481     sizeof(CDataObject),                        /* tp_basicsize */
   4482     0,                                          /* tp_itemsize */
   4483     0,                                          /* tp_dealloc */
   4484     0,                                          /* tp_print */
   4485     0,                                          /* tp_getattr */
   4486     0,                                          /* tp_setattr */
   4487     0,                                          /* tp_reserved */
   4488     0,                                          /* tp_repr */
   4489     0,                                          /* tp_as_number */
   4490     &Array_as_sequence,                         /* tp_as_sequence */
   4491     &Array_as_mapping,                          /* tp_as_mapping */
   4492     0,                                          /* tp_hash */
   4493     0,                                          /* tp_call */
   4494     0,                                          /* tp_str */
   4495     0,                                          /* tp_getattro */
   4496     0,                                          /* tp_setattro */
   4497     &PyCData_as_buffer,                         /* tp_as_buffer */
   4498     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
   4499     "XXX to be provided",                       /* tp_doc */
   4500     (traverseproc)PyCData_traverse,             /* tp_traverse */
   4501     (inquiry)PyCData_clear,                     /* tp_clear */
   4502     0,                                          /* tp_richcompare */
   4503     0,                                          /* tp_weaklistoffset */
   4504     0,                                          /* tp_iter */
   4505     0,                                          /* tp_iternext */
   4506     0,                                          /* tp_methods */
   4507     0,                                          /* tp_members */
   4508     0,                                          /* tp_getset */
   4509     0,                                          /* tp_base */
   4510     0,                                          /* tp_dict */
   4511     0,                                          /* tp_descr_get */
   4512     0,                                          /* tp_descr_set */
   4513     0,                                          /* tp_dictoffset */
   4514     (initproc)Array_init,                       /* tp_init */
   4515     0,                                          /* tp_alloc */
   4516     GenericPyCData_new,                         /* tp_new */
   4517     0,                                          /* tp_free */
   4518 };
   4519 
   4520 PyObject *
   4521 PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length)
   4522 {
   4523     static PyObject *cache;
   4524     PyObject *key;
   4525     PyObject *result;
   4526     char name[256];
   4527     PyObject *len;
   4528 
   4529     if (cache == NULL) {
   4530         cache = PyDict_New();
   4531         if (cache == NULL)
   4532             return NULL;
   4533     }
   4534     len = PyLong_FromSsize_t(length);
   4535     if (len == NULL)
   4536         return NULL;
   4537     key = PyTuple_Pack(2, itemtype, len);
   4538     Py_DECREF(len);
   4539     if (!key)
   4540         return NULL;
   4541     result = PyDict_GetItemProxy(cache, key);
   4542     if (result) {
   4543         Py_INCREF(result);
   4544         Py_DECREF(key);
   4545         return result;
   4546     }
   4547 
   4548     if (!PyType_Check(itemtype)) {
   4549         PyErr_SetString(PyExc_TypeError,
   4550                         "Expected a type object");
   4551         Py_DECREF(key);
   4552         return NULL;
   4553     }
   4554 #ifdef MS_WIN64
   4555     sprintf(name, "%.200s_Array_%Id",
   4556         ((PyTypeObject *)itemtype)->tp_name, length);
   4557 #else
   4558     sprintf(name, "%.200s_Array_%ld",
   4559         ((PyTypeObject *)itemtype)->tp_name, (long)length);
   4560 #endif
   4561 
   4562     result = PyObject_CallFunction((PyObject *)&PyCArrayType_Type,
   4563                                    "s(O){s:n,s:O}",
   4564                                    name,
   4565                                    &PyCArray_Type,
   4566                                    "_length_",
   4567                                    length,
   4568                                    "_type_",
   4569                                    itemtype
   4570         );
   4571     if (result == NULL) {
   4572         Py_DECREF(key);
   4573         return NULL;
   4574     }
   4575     if (-1 == PyDict_SetItemProxy(cache, key, result)) {
   4576         Py_DECREF(key);
   4577         Py_DECREF(result);
   4578         return NULL;
   4579     }
   4580     Py_DECREF(key);
   4581     return result;
   4582 }
   4583 
   4584 
   4585 /******************************************************************/
   4586 /*
   4587   Simple_Type
   4588 */
   4589 
   4590 static int
   4591 Simple_set_value(CDataObject *self, PyObject *value)
   4592 {
   4593     PyObject *result;
   4594     StgDictObject *dict = PyObject_stgdict((PyObject *)self);
   4595 
   4596     if (value == NULL) {
   4597         PyErr_SetString(PyExc_TypeError,
   4598                         "can't delete attribute");
   4599         return -1;
   4600     }
   4601     assert(dict); /* Cannot be NULL for CDataObject instances */
   4602     assert(dict->setfunc);
   4603     result = dict->setfunc(self->b_ptr, value, dict->size);
   4604     if (!result)
   4605         return -1;
   4606 
   4607     /* consumes the refcount the setfunc returns */
   4608     return KeepRef(self, 0, result);
   4609 }
   4610 
   4611 static int
   4612 Simple_init(CDataObject *self, PyObject *args, PyObject *kw)
   4613 {
   4614     PyObject *value = NULL;
   4615     if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value))
   4616         return -1;
   4617     if (value)
   4618         return Simple_set_value(self, value);
   4619     return 0;
   4620 }
   4621 
   4622 static PyObject *
   4623 Simple_get_value(CDataObject *self)
   4624 {
   4625     StgDictObject *dict;
   4626     dict = PyObject_stgdict((PyObject *)self);
   4627     assert(dict); /* Cannot be NULL for CDataObject instances */
   4628     assert(dict->getfunc);
   4629     return dict->getfunc(self->b_ptr, self->b_size);
   4630 }
   4631 
   4632 static PyGetSetDef Simple_getsets[] = {
   4633     { "value", (getter)Simple_get_value, (setter)Simple_set_value,
   4634       "current value", NULL },
   4635     { NULL, NULL }
   4636 };
   4637 
   4638 static PyObject *
   4639 Simple_from_outparm(PyObject *self, PyObject *args)
   4640 {
   4641     if (_ctypes_simple_instance((PyObject *)Py_TYPE(self))) {
   4642         Py_INCREF(self);
   4643         return self;
   4644     }
   4645     /* call stgdict->getfunc */
   4646     return Simple_get_value((CDataObject *)self);
   4647 }
   4648 
   4649 static PyMethodDef Simple_methods[] = {
   4650     { "__ctypes_from_outparam__", Simple_from_outparm, METH_NOARGS, },
   4651     { NULL, NULL },
   4652 };
   4653 
   4654 static int Simple_bool(CDataObject *self)
   4655 {
   4656     return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size);
   4657 }
   4658 
   4659 static PyNumberMethods Simple_as_number = {
   4660     0, /* nb_add */
   4661     0, /* nb_subtract */
   4662     0, /* nb_multiply */
   4663     0, /* nb_remainder */
   4664     0, /* nb_divmod */
   4665     0, /* nb_power */
   4666     0, /* nb_negative */
   4667     0, /* nb_positive */
   4668     0, /* nb_absolute */
   4669     (inquiry)Simple_bool, /* nb_bool */
   4670 };
   4671 
   4672 /* "%s(%s)" % (self.__class__.__name__, self.value) */
   4673 static PyObject *
   4674 Simple_repr(CDataObject *self)
   4675 {
   4676     PyObject *val, *result;
   4677 
   4678     if (Py_TYPE(self)->tp_base != &Simple_Type) {
   4679         return PyUnicode_FromFormat("<%s object at %p>",
   4680                                    Py_TYPE(self)->tp_name, self);
   4681     }
   4682 
   4683     val = Simple_get_value(self);
   4684     if (val == NULL)
   4685         return NULL;
   4686 
   4687     result = PyUnicode_FromFormat("%s(%R)",
   4688                                   Py_TYPE(self)->tp_name, val);
   4689     Py_DECREF(val);
   4690     return result;
   4691 }
   4692 
   4693 static PyTypeObject Simple_Type = {
   4694     PyVarObject_HEAD_INIT(NULL, 0)
   4695     "_ctypes._SimpleCData",
   4696     sizeof(CDataObject),                        /* tp_basicsize */
   4697     0,                                          /* tp_itemsize */
   4698     0,                                          /* tp_dealloc */
   4699     0,                                          /* tp_print */
   4700     0,                                          /* tp_getattr */
   4701     0,                                          /* tp_setattr */
   4702     0,                                          /* tp_reserved */
   4703     (reprfunc)&Simple_repr,                     /* tp_repr */
   4704     &Simple_as_number,                          /* tp_as_number */
   4705     0,                                          /* tp_as_sequence */
   4706     0,                                          /* tp_as_mapping */
   4707     0,                                          /* tp_hash */
   4708     0,                                          /* tp_call */
   4709     0,                                          /* tp_str */
   4710     0,                                          /* tp_getattro */
   4711     0,                                          /* tp_setattro */
   4712     &PyCData_as_buffer,                         /* tp_as_buffer */
   4713     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
   4714     "XXX to be provided",                       /* tp_doc */
   4715     (traverseproc)PyCData_traverse,             /* tp_traverse */
   4716     (inquiry)PyCData_clear,                     /* tp_clear */
   4717     0,                                          /* tp_richcompare */
   4718     0,                                          /* tp_weaklistoffset */
   4719     0,                                          /* tp_iter */
   4720     0,                                          /* tp_iternext */
   4721     Simple_methods,                             /* tp_methods */
   4722     0,                                          /* tp_members */
   4723     Simple_getsets,                             /* tp_getset */
   4724     0,                                          /* tp_base */
   4725     0,                                          /* tp_dict */
   4726     0,                                          /* tp_descr_get */
   4727     0,                                          /* tp_descr_set */
   4728     0,                                          /* tp_dictoffset */
   4729     (initproc)Simple_init,                      /* tp_init */
   4730     0,                                          /* tp_alloc */
   4731     GenericPyCData_new,                         /* tp_new */
   4732     0,                                          /* tp_free */
   4733 };
   4734 
   4735 /******************************************************************/
   4736 /*
   4737   PyCPointer_Type
   4738 */
   4739 static PyObject *
   4740 Pointer_item(PyObject *myself, Py_ssize_t index)
   4741 {
   4742     CDataObject *self = (CDataObject *)myself;
   4743     Py_ssize_t size;
   4744     Py_ssize_t offset;
   4745     StgDictObject *stgdict, *itemdict;
   4746     PyObject *proto;
   4747 
   4748     if (*(void **)self->b_ptr == NULL) {
   4749         PyErr_SetString(PyExc_ValueError,
   4750                         "NULL pointer access");
   4751         return NULL;
   4752     }
   4753 
   4754     stgdict = PyObject_stgdict((PyObject *)self);
   4755     assert(stgdict); /* Cannot be NULL for pointer object instances */
   4756 
   4757     proto = stgdict->proto;
   4758     assert(proto);
   4759     itemdict = PyType_stgdict(proto);
   4760     assert(itemdict); /* proto is the item type of the pointer, a ctypes
   4761                          type, so this cannot be NULL */
   4762 
   4763     size = itemdict->size;
   4764     offset = index * itemdict->size;
   4765 
   4766     return PyCData_get(proto, stgdict->getfunc, (PyObject *)self,
   4767                      index, size, (*(char **)self->b_ptr) + offset);
   4768 }
   4769 
   4770 static int
   4771 Pointer_ass_item(PyObject *myself, Py_ssize_t index, PyObject *value)
   4772 {
   4773     CDataObject *self = (CDataObject *)myself;
   4774     Py_ssize_t size;
   4775     Py_ssize_t offset;
   4776     StgDictObject *stgdict, *itemdict;
   4777     PyObject *proto;
   4778 
   4779     if (value == NULL) {
   4780         PyErr_SetString(PyExc_TypeError,
   4781                         "Pointer does not support item deletion");
   4782         return -1;
   4783     }
   4784 
   4785     if (*(void **)self->b_ptr == NULL) {
   4786         PyErr_SetString(PyExc_ValueError,
   4787                         "NULL pointer access");
   4788         return -1;
   4789     }
   4790 
   4791     stgdict = PyObject_stgdict((PyObject *)self);
   4792     assert(stgdict); /* Cannot be NULL fr pointer instances */
   4793 
   4794     proto = stgdict->proto;
   4795     assert(proto);
   4796 
   4797     itemdict = PyType_stgdict(proto);
   4798     assert(itemdict); /* Cannot be NULL because the itemtype of a pointer
   4799                          is always a ctypes type */
   4800 
   4801     size = itemdict->size;
   4802     offset = index * itemdict->size;
   4803 
   4804     return PyCData_set((PyObject *)self, proto, stgdict->setfunc, value,
   4805                      index, size, (*(char **)self->b_ptr) + offset);
   4806 }
   4807 
   4808 static PyObject *
   4809 Pointer_get_contents(CDataObject *self, void *closure)
   4810 {
   4811     StgDictObject *stgdict;
   4812 
   4813     if (*(void **)self->b_ptr == NULL) {
   4814         PyErr_SetString(PyExc_ValueError,
   4815                         "NULL pointer access");
   4816         return NULL;
   4817     }
   4818 
   4819     stgdict = PyObject_stgdict((PyObject *)self);
   4820     assert(stgdict); /* Cannot be NULL fr pointer instances */
   4821     return PyCData_FromBaseObj(stgdict->proto,
   4822                              (PyObject *)self, 0,
   4823                              *(void **)self->b_ptr);
   4824 }
   4825 
   4826 static int
   4827 Pointer_set_contents(CDataObject *self, PyObject *value, void *closure)
   4828 {
   4829     StgDictObject *stgdict;
   4830     CDataObject *dst;
   4831     PyObject *keep;
   4832 
   4833     if (value == NULL) {
   4834         PyErr_SetString(PyExc_TypeError,
   4835                         "Pointer does not support item deletion");
   4836         return -1;
   4837     }
   4838     stgdict = PyObject_stgdict((PyObject *)self);
   4839     assert(stgdict); /* Cannot be NULL fr pointer instances */
   4840     assert(stgdict->proto);
   4841     if (!CDataObject_Check(value)) {
   4842         int res = PyObject_IsInstance(value, stgdict->proto);
   4843         if (res == -1)
   4844             return -1;
   4845         if (!res) {
   4846             PyErr_Format(PyExc_TypeError,
   4847                          "expected %s instead of %s",
   4848                          ((PyTypeObject *)(stgdict->proto))->tp_name,
   4849                          Py_TYPE(value)->tp_name);
   4850             return -1;
   4851         }
   4852     }
   4853 
   4854     dst = (CDataObject *)value;
   4855     *(void **)self->b_ptr = dst->b_ptr;
   4856 
   4857     /*
   4858        A Pointer instance must keep the value it points to alive.  So, a
   4859        pointer instance has b_length set to 2 instead of 1, and we set
   4860        'value' itself as the second item of the b_objects list, additionally.
   4861     */
   4862     Py_INCREF(value);
   4863     if (-1 == KeepRef(self, 1, value))
   4864         return -1;
   4865 
   4866     keep = GetKeepedObjects(dst);
   4867     if (keep == NULL)
   4868         return -1;
   4869 
   4870     Py_INCREF(keep);
   4871     return KeepRef(self, 0, keep);
   4872 }
   4873 
   4874 static PyGetSetDef Pointer_getsets[] = {
   4875     { "contents", (getter)Pointer_get_contents,
   4876       (setter)Pointer_set_contents,
   4877       "the object this pointer points to (read-write)", NULL },
   4878     { NULL, NULL }
   4879 };
   4880 
   4881 static int
   4882 Pointer_init(CDataObject *self, PyObject *args, PyObject *kw)
   4883 {
   4884     PyObject *value = NULL;
   4885 
   4886     if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value))
   4887         return -1;
   4888     if (value == NULL)
   4889         return 0;
   4890     return Pointer_set_contents(self, value, NULL);
   4891 }
   4892 
   4893 static PyObject *
   4894 Pointer_new(PyTypeObject *type, PyObject *args, PyObject *kw)
   4895 {
   4896     StgDictObject *dict = PyType_stgdict((PyObject *)type);
   4897     if (!dict || !dict->proto) {
   4898         PyErr_SetString(PyExc_TypeError,
   4899                         "Cannot create instance: has no _type_");
   4900         return NULL;
   4901     }
   4902     return GenericPyCData_new(type, args, kw);
   4903 }
   4904 
   4905 static PyObject *
   4906 Pointer_subscript(PyObject *myself, PyObject *item)
   4907 {
   4908     CDataObject *self = (CDataObject *)myself;
   4909     if (PyIndex_Check(item)) {
   4910         Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
   4911         if (i == -1 && PyErr_Occurred())
   4912             return NULL;
   4913         return Pointer_item(myself, i);
   4914     }
   4915     else if (PySlice_Check(item)) {
   4916         PySliceObject *slice = (PySliceObject *)item;
   4917         Py_ssize_t start, stop, step;
   4918         PyObject *np;
   4919         StgDictObject *stgdict, *itemdict;
   4920         PyObject *proto;
   4921         Py_ssize_t i, len, cur;
   4922 
   4923         /* Since pointers have no length, and we want to apply
   4924            different semantics to negative indices than normal
   4925            slicing, we have to dissect the slice object ourselves.*/
   4926         if (slice->step == Py_None) {
   4927             step = 1;
   4928         }
   4929         else {
   4930             step = PyNumber_AsSsize_t(slice->step,
   4931                                       PyExc_ValueError);
   4932             if (step == -1 && PyErr_Occurred())
   4933                 return NULL;
   4934             if (step == 0) {
   4935                 PyErr_SetString(PyExc_ValueError,
   4936                                 "slice step cannot be zero");
   4937                 return NULL;
   4938             }
   4939         }
   4940         if (slice->start == Py_None) {
   4941             if (step < 0) {
   4942                 PyErr_SetString(PyExc_ValueError,
   4943                                 "slice start is required "
   4944                                 "for step < 0");
   4945                 return NULL;
   4946             }
   4947             start = 0;
   4948         }
   4949         else {
   4950             start = PyNumber_AsSsize_t(slice->start,
   4951                                        PyExc_ValueError);
   4952             if (start == -1 && PyErr_Occurred())
   4953                 return NULL;
   4954         }
   4955         if (slice->stop == Py_None) {
   4956             PyErr_SetString(PyExc_ValueError,
   4957                             "slice stop is required");
   4958             return NULL;
   4959         }
   4960         stop = PyNumber_AsSsize_t(slice->stop,
   4961                                   PyExc_ValueError);
   4962         if (stop == -1 && PyErr_Occurred())
   4963             return NULL;
   4964         if ((step > 0 && start > stop) ||
   4965             (step < 0 && start < stop))
   4966             len = 0;
   4967         else if (step > 0)
   4968             len = (stop - start - 1) / step + 1;
   4969         else
   4970             len = (stop - start + 1) / step + 1;
   4971 
   4972         stgdict = PyObject_stgdict((PyObject *)self);
   4973         assert(stgdict); /* Cannot be NULL for pointer instances */
   4974         proto = stgdict->proto;
   4975         assert(proto);
   4976         itemdict = PyType_stgdict(proto);
   4977         assert(itemdict);
   4978         if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
   4979             char *ptr = *(char **)self->b_ptr;
   4980             char *dest;
   4981 
   4982             if (len <= 0)
   4983                 return PyBytes_FromStringAndSize("", 0);
   4984             if (step == 1) {
   4985                 return PyBytes_FromStringAndSize(ptr + start,
   4986                                                  len);
   4987             }
   4988             dest = (char *)PyMem_Malloc(len);
   4989             if (dest == NULL)
   4990                 return PyErr_NoMemory();
   4991             for (cur = start, i = 0; i < len; cur += step, i++) {
   4992                 dest[i] = ptr[cur];
   4993             }
   4994             np = PyBytes_FromStringAndSize(dest, len);
   4995             PyMem_Free(dest);
   4996             return np;
   4997         }
   4998 #ifdef CTYPES_UNICODE
   4999         if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
   5000             wchar_t *ptr = *(wchar_t **)self->b_ptr;
   5001             wchar_t *dest;
   5002 
   5003             if (len <= 0)
   5004                 return PyUnicode_New(0, 0);
   5005             if (step == 1) {
   5006                 return PyUnicode_FromWideChar(ptr + start,
   5007                                               len);
   5008             }
   5009             dest = PyMem_New(wchar_t, len);
   5010             if (dest == NULL)
   5011                 return PyErr_NoMemory();
   5012             for (cur = start, i = 0; i < len; cur += step, i++) {
   5013                 dest[i] = ptr[cur];
   5014             }
   5015             np = PyUnicode_FromWideChar(dest, len);
   5016             PyMem_Free(dest);
   5017             return np;
   5018         }
   5019 #endif
   5020 
   5021         np = PyList_New(len);
   5022         if (np == NULL)
   5023             return NULL;
   5024 
   5025         for (cur = start, i = 0; i < len; cur += step, i++) {
   5026             PyObject *v = Pointer_item(myself, cur);
   5027             PyList_SET_ITEM(np, i, v);
   5028         }
   5029         return np;
   5030     }
   5031     else {
   5032         PyErr_SetString(PyExc_TypeError,
   5033                         "Pointer indices must be integer");
   5034         return NULL;
   5035     }
   5036 }
   5037 
   5038 static PySequenceMethods Pointer_as_sequence = {
   5039     0,                                          /* inquiry sq_length; */
   5040     0,                                          /* binaryfunc sq_concat; */
   5041     0,                                          /* intargfunc sq_repeat; */
   5042     Pointer_item,                               /* intargfunc sq_item; */
   5043     0,                                          /* intintargfunc sq_slice; */
   5044     Pointer_ass_item,                           /* intobjargproc sq_ass_item; */
   5045     0,                                          /* intintobjargproc sq_ass_slice; */
   5046     0,                                          /* objobjproc sq_contains; */
   5047     /* Added in release 2.0 */
   5048     0,                                          /* binaryfunc sq_inplace_concat; */
   5049     0,                                          /* intargfunc sq_inplace_repeat; */
   5050 };
   5051 
   5052 static PyMappingMethods Pointer_as_mapping = {
   5053     0,
   5054     Pointer_subscript,
   5055 };
   5056 
   5057 static int
   5058 Pointer_bool(CDataObject *self)
   5059 {
   5060     return (*(void **)self->b_ptr != NULL);
   5061 }
   5062 
   5063 static PyNumberMethods Pointer_as_number = {
   5064     0, /* nb_add */
   5065     0, /* nb_subtract */
   5066     0, /* nb_multiply */
   5067     0, /* nb_remainder */
   5068     0, /* nb_divmod */
   5069     0, /* nb_power */
   5070     0, /* nb_negative */
   5071     0, /* nb_positive */
   5072     0, /* nb_absolute */
   5073     (inquiry)Pointer_bool, /* nb_bool */
   5074 };
   5075 
   5076 PyTypeObject PyCPointer_Type = {
   5077     PyVarObject_HEAD_INIT(NULL, 0)
   5078     "_ctypes._Pointer",
   5079     sizeof(CDataObject),                        /* tp_basicsize */
   5080     0,                                          /* tp_itemsize */
   5081     0,                                          /* tp_dealloc */
   5082     0,                                          /* tp_print */
   5083     0,                                          /* tp_getattr */
   5084     0,                                          /* tp_setattr */
   5085     0,                                          /* tp_reserved */
   5086     0,                                          /* tp_repr */
   5087     &Pointer_as_number,                         /* tp_as_number */
   5088     &Pointer_as_sequence,                       /* tp_as_sequence */
   5089     &Pointer_as_mapping,                        /* tp_as_mapping */
   5090     0,                                          /* tp_hash */
   5091     0,                                          /* tp_call */
   5092     0,                                          /* tp_str */
   5093     0,                                          /* tp_getattro */
   5094     0,                                          /* tp_setattro */
   5095     &PyCData_as_buffer,                         /* tp_as_buffer */
   5096     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
   5097     "XXX to be provided",                       /* tp_doc */
   5098     (traverseproc)PyCData_traverse,             /* tp_traverse */
   5099     (inquiry)PyCData_clear,                     /* tp_clear */
   5100     0,                                          /* tp_richcompare */
   5101     0,                                          /* tp_weaklistoffset */
   5102     0,                                          /* tp_iter */
   5103     0,                                          /* tp_iternext */
   5104     0,                                          /* tp_methods */
   5105     0,                                          /* tp_members */
   5106     Pointer_getsets,                            /* tp_getset */
   5107     0,                                          /* tp_base */
   5108     0,                                          /* tp_dict */
   5109     0,                                          /* tp_descr_get */
   5110     0,                                          /* tp_descr_set */
   5111     0,                                          /* tp_dictoffset */
   5112     (initproc)Pointer_init,                     /* tp_init */
   5113     0,                                          /* tp_alloc */
   5114     Pointer_new,                                /* tp_new */
   5115     0,                                          /* tp_free */
   5116 };
   5117 
   5118 
   5119 /******************************************************************/
   5120 /*
   5121  *  Module initialization.
   5122  */
   5123 
   5124 static const char module_docs[] =
   5125 "Create and manipulate C compatible data types in Python.";
   5126 
   5127 #ifdef MS_WIN32
   5128 
   5129 static const char comerror_doc[] = "Raised when a COM method call failed.";
   5130 
   5131 int
   5132 comerror_init(PyObject *self, PyObject *args, PyObject *kwds)
   5133 {
   5134     PyObject *hresult, *text, *details;
   5135     PyObject *a;
   5136     int status;
   5137 
   5138     if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
   5139         return -1;
   5140 
   5141     if (!PyArg_ParseTuple(args, "OOO:COMError", &hresult, &text, &details))
   5142         return -1;
   5143 
   5144     a = PySequence_GetSlice(args, 1, PySequence_Size(args));
   5145     if (!a)
   5146         return -1;
   5147     status = PyObject_SetAttrString(self, "args", a);
   5148     Py_DECREF(a);
   5149     if (status < 0)
   5150         return -1;
   5151 
   5152     if (PyObject_SetAttrString(self, "hresult", hresult) < 0)
   5153         return -1;
   5154 
   5155     if (PyObject_SetAttrString(self, "text", text) < 0)
   5156         return -1;
   5157 
   5158     if (PyObject_SetAttrString(self, "details", details) < 0)
   5159         return -1;
   5160 
   5161     Py_INCREF(args);
   5162     Py_SETREF(((PyBaseExceptionObject *)self)->args, args);
   5163 
   5164     return 0;
   5165 }
   5166 
   5167 static PyTypeObject PyComError_Type = {
   5168     PyVarObject_HEAD_INIT(NULL, 0)
   5169     "_ctypes.COMError",         /* tp_name */
   5170     sizeof(PyBaseExceptionObject), /* tp_basicsize */
   5171     0,                          /* tp_itemsize */
   5172     0,                          /* tp_dealloc */
   5173     0,                          /* tp_print */
   5174     0,                          /* tp_getattr */
   5175     0,                          /* tp_setattr */
   5176     0,                          /* tp_reserved */
   5177     0,                          /* tp_repr */
   5178     0,                          /* tp_as_number */
   5179     0,                          /* tp_as_sequence */
   5180     0,                          /* tp_as_mapping */
   5181     0,                          /* tp_hash */
   5182     0,                          /* tp_call */
   5183     0,                          /* tp_str */
   5184     0,                          /* tp_getattro */
   5185     0,                          /* tp_setattro */
   5186     0,                          /* tp_as_buffer */
   5187     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
   5188     PyDoc_STR(comerror_doc),    /* tp_doc */
   5189     0,                          /* tp_traverse */
   5190     0,                          /* tp_clear */
   5191     0,                          /* tp_richcompare */
   5192     0,                          /* tp_weaklistoffset */
   5193     0,                          /* tp_iter */
   5194     0,                          /* tp_iternext */
   5195     0,                          /* tp_methods */
   5196     0,                          /* tp_members */
   5197     0,                          /* tp_getset */
   5198     0,                          /* tp_base */
   5199     0,                          /* tp_dict */
   5200     0,                          /* tp_descr_get */
   5201     0,                          /* tp_descr_set */
   5202     0,                          /* tp_dictoffset */
   5203     (initproc)comerror_init,    /* tp_init */
   5204     0,                          /* tp_alloc */
   5205     0,                          /* tp_new */
   5206 };
   5207 
   5208 
   5209 static int
   5210 create_comerror(void)
   5211 {
   5212     PyComError_Type.tp_base = (PyTypeObject*)PyExc_Exception;
   5213     if (PyType_Ready(&PyComError_Type) < 0)
   5214         return -1;
   5215     Py_INCREF(&PyComError_Type);
   5216     ComError = (PyObject*)&PyComError_Type;
   5217     return 0;
   5218 }
   5219 
   5220 #endif
   5221 
   5222 static PyObject *
   5223 string_at(const char *ptr, int size)
   5224 {
   5225     if (size == -1)
   5226         return PyBytes_FromStringAndSize(ptr, strlen(ptr));
   5227     return PyBytes_FromStringAndSize(ptr, size);
   5228 }
   5229 
   5230 static int
   5231 cast_check_pointertype(PyObject *arg)
   5232 {
   5233     StgDictObject *dict;
   5234 
   5235     if (PyCPointerTypeObject_Check(arg))
   5236         return 1;
   5237     if (PyCFuncPtrTypeObject_Check(arg))
   5238         return 1;
   5239     dict = PyType_stgdict(arg);
   5240     if (dict) {
   5241         if (PyUnicode_Check(dict->proto)
   5242             && (strchr("sPzUZXO", PyUnicode_AsUTF8(dict->proto)[0]))) {
   5243             /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
   5244             return 1;
   5245         }
   5246     }
   5247     PyErr_Format(PyExc_TypeError,
   5248                  "cast() argument 2 must be a pointer type, not %s",
   5249                  PyType_Check(arg)
   5250                  ? ((PyTypeObject *)arg)->tp_name
   5251                  : Py_TYPE(arg)->tp_name);
   5252     return 0;
   5253 }
   5254 
   5255 static PyObject *
   5256 cast(void *ptr, PyObject *src, PyObject *ctype)
   5257 {
   5258     CDataObject *result;
   5259     if (0 == cast_check_pointertype(ctype))
   5260         return NULL;
   5261     result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL);
   5262     if (result == NULL)
   5263         return NULL;
   5264 
   5265     /*
   5266       The casted objects '_objects' member:
   5267 
   5268       It must certainly contain the source objects one.
   5269       It must contain the source object itself.
   5270      */
   5271     if (CDataObject_Check(src)) {
   5272         CDataObject *obj = (CDataObject *)src;
   5273         CDataObject *container;
   5274 
   5275         /* PyCData_GetContainer will initialize src.b_objects, we need
   5276            this so it can be shared */
   5277         container = PyCData_GetContainer(obj);
   5278         if (container == NULL)
   5279             goto failed;
   5280 
   5281         /* But we need a dictionary! */
   5282         if (obj->b_objects == Py_None) {
   5283             Py_DECREF(Py_None);
   5284             obj->b_objects = PyDict_New();
   5285             if (obj->b_objects == NULL)
   5286                 goto failed;
   5287         }
   5288         Py_XINCREF(obj->b_objects);
   5289         result->b_objects = obj->b_objects;
   5290         if (result->b_objects && PyDict_CheckExact(result->b_objects)) {
   5291             PyObject *index;
   5292             int rc;
   5293             index = PyLong_FromVoidPtr((void *)src);
   5294             if (index == NULL)
   5295                 goto failed;
   5296             rc = PyDict_SetItem(result->b_objects, index, src);
   5297             Py_DECREF(index);
   5298             if (rc == -1)
   5299                 goto failed;
   5300         }
   5301     }
   5302     /* Should we assert that result is a pointer type? */
   5303     memcpy(result->b_ptr, &ptr, sizeof(void *));
   5304     return (PyObject *)result;
   5305 
   5306   failed:
   5307     Py_DECREF(result);
   5308     return NULL;
   5309 }
   5310 
   5311 #ifdef CTYPES_UNICODE
   5312 static PyObject *
   5313 wstring_at(const wchar_t *ptr, int size)
   5314 {
   5315     Py_ssize_t ssize = size;
   5316     if (ssize == -1)
   5317         ssize = wcslen(ptr);
   5318     return PyUnicode_FromWideChar(ptr, ssize);
   5319 }
   5320 #endif
   5321 
   5322 
   5323 static struct PyModuleDef _ctypesmodule = {
   5324     PyModuleDef_HEAD_INIT,
   5325     "_ctypes",
   5326     module_docs,
   5327     -1,
   5328     _ctypes_module_methods,
   5329     NULL,
   5330     NULL,
   5331     NULL,
   5332     NULL
   5333 };
   5334 
   5335 PyMODINIT_FUNC
   5336 PyInit__ctypes(void)
   5337 {
   5338     PyObject *m;
   5339 
   5340 /* Note:
   5341    ob_type is the metatype (the 'type'), defaults to PyType_Type,
   5342    tp_base is the base type, defaults to 'object' aka PyBaseObject_Type.
   5343 */
   5344 #ifdef WITH_THREAD
   5345     PyEval_InitThreads();
   5346 #endif
   5347     m = PyModule_Create(&_ctypesmodule);
   5348     if (!m)
   5349         return NULL;
   5350 
   5351     _ctypes_ptrtype_cache = PyDict_New();
   5352     if (_ctypes_ptrtype_cache == NULL)
   5353         return NULL;
   5354 
   5355     PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_ctypes_ptrtype_cache);
   5356 
   5357     _unpickle = PyObject_GetAttrString(m, "_unpickle");
   5358     if (_unpickle == NULL)
   5359         return NULL;
   5360 
   5361     if (PyType_Ready(&PyCArg_Type) < 0)
   5362         return NULL;
   5363 
   5364     if (PyType_Ready(&PyCThunk_Type) < 0)
   5365         return NULL;
   5366 
   5367     /* StgDict is derived from PyDict_Type */
   5368     PyCStgDict_Type.tp_base = &PyDict_Type;
   5369     if (PyType_Ready(&PyCStgDict_Type) < 0)
   5370         return NULL;
   5371 
   5372     /*************************************************
   5373      *
   5374      * Metaclasses
   5375      */
   5376 
   5377     PyCStructType_Type.tp_base = &PyType_Type;
   5378     if (PyType_Ready(&PyCStructType_Type) < 0)
   5379         return NULL;
   5380 
   5381     UnionType_Type.tp_base = &PyType_Type;
   5382     if (PyType_Ready(&UnionType_Type) < 0)
   5383         return NULL;
   5384 
   5385     PyCPointerType_Type.tp_base = &PyType_Type;
   5386     if (PyType_Ready(&PyCPointerType_Type) < 0)
   5387         return NULL;
   5388 
   5389     PyCArrayType_Type.tp_base = &PyType_Type;
   5390     if (PyType_Ready(&PyCArrayType_Type) < 0)
   5391         return NULL;
   5392 
   5393     PyCSimpleType_Type.tp_base = &PyType_Type;
   5394     if (PyType_Ready(&PyCSimpleType_Type) < 0)
   5395         return NULL;
   5396 
   5397     PyCFuncPtrType_Type.tp_base = &PyType_Type;
   5398     if (PyType_Ready(&PyCFuncPtrType_Type) < 0)
   5399         return NULL;
   5400 
   5401     /*************************************************
   5402      *
   5403      * Classes using a custom metaclass
   5404      */
   5405 
   5406     if (PyType_Ready(&PyCData_Type) < 0)
   5407         return NULL;
   5408 
   5409     Py_TYPE(&Struct_Type) = &PyCStructType_Type;
   5410     Struct_Type.tp_base = &PyCData_Type;
   5411     if (PyType_Ready(&Struct_Type) < 0)
   5412         return NULL;
   5413     Py_INCREF(&Struct_Type);
   5414     PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type);
   5415 
   5416     Py_TYPE(&Union_Type) = &UnionType_Type;
   5417     Union_Type.tp_base = &PyCData_Type;
   5418     if (PyType_Ready(&Union_Type) < 0)
   5419         return NULL;
   5420     Py_INCREF(&Union_Type);
   5421     PyModule_AddObject(m, "Union", (PyObject *)&Union_Type);
   5422 
   5423     Py_TYPE(&PyCPointer_Type) = &PyCPointerType_Type;
   5424     PyCPointer_Type.tp_base = &PyCData_Type;
   5425     if (PyType_Ready(&PyCPointer_Type) < 0)
   5426         return NULL;
   5427     Py_INCREF(&PyCPointer_Type);
   5428     PyModule_AddObject(m, "_Pointer", (PyObject *)&PyCPointer_Type);
   5429 
   5430     Py_TYPE(&PyCArray_Type) = &PyCArrayType_Type;
   5431     PyCArray_Type.tp_base = &PyCData_Type;
   5432     if (PyType_Ready(&PyCArray_Type) < 0)
   5433         return NULL;
   5434     Py_INCREF(&PyCArray_Type);
   5435     PyModule_AddObject(m, "Array", (PyObject *)&PyCArray_Type);
   5436 
   5437     Py_TYPE(&Simple_Type) = &PyCSimpleType_Type;
   5438     Simple_Type.tp_base = &PyCData_Type;
   5439     if (PyType_Ready(&Simple_Type) < 0)
   5440         return NULL;
   5441     Py_INCREF(&Simple_Type);
   5442     PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type);
   5443 
   5444     Py_TYPE(&PyCFuncPtr_Type) = &PyCFuncPtrType_Type;
   5445     PyCFuncPtr_Type.tp_base = &PyCData_Type;
   5446     if (PyType_Ready(&PyCFuncPtr_Type) < 0)
   5447         return NULL;
   5448     Py_INCREF(&PyCFuncPtr_Type);
   5449     PyModule_AddObject(m, "CFuncPtr", (PyObject *)&PyCFuncPtr_Type);
   5450 
   5451     /*************************************************
   5452      *
   5453      * Simple classes
   5454      */
   5455 
   5456     /* PyCField_Type is derived from PyBaseObject_Type */
   5457     if (PyType_Ready(&PyCField_Type) < 0)
   5458         return NULL;
   5459 
   5460     /*************************************************
   5461      *
   5462      * Other stuff
   5463      */
   5464 
   5465     DictRemover_Type.tp_new = PyType_GenericNew;
   5466     if (PyType_Ready(&DictRemover_Type) < 0)
   5467         return NULL;
   5468 
   5469 #ifdef MS_WIN32
   5470     if (create_comerror() < 0)
   5471         return NULL;
   5472     PyModule_AddObject(m, "COMError", ComError);
   5473 
   5474     PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyLong_FromLong(FUNCFLAG_HRESULT));
   5475     PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyLong_FromLong(FUNCFLAG_STDCALL));
   5476 #endif
   5477     PyModule_AddObject(m, "FUNCFLAG_CDECL", PyLong_FromLong(FUNCFLAG_CDECL));
   5478     PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyLong_FromLong(FUNCFLAG_USE_ERRNO));
   5479     PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyLong_FromLong(FUNCFLAG_USE_LASTERROR));
   5480     PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyLong_FromLong(FUNCFLAG_PYTHONAPI));
   5481     PyModule_AddStringConstant(m, "__version__", "1.1.0");
   5482 
   5483     PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove));
   5484     PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset));
   5485     PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at));
   5486     PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast));
   5487 #ifdef CTYPES_UNICODE
   5488     PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at));
   5489 #endif
   5490 
   5491 /* If RTLD_LOCAL is not defined (Windows!), set it to zero. */
   5492 #if !HAVE_DECL_RTLD_LOCAL
   5493 #define RTLD_LOCAL 0
   5494 #endif
   5495 
   5496 /* If RTLD_GLOBAL is not defined (cygwin), set it to the same value as
   5497    RTLD_LOCAL.
   5498 */
   5499 #if !HAVE_DECL_RTLD_GLOBAL
   5500 #define RTLD_GLOBAL RTLD_LOCAL
   5501 #endif
   5502 
   5503     PyModule_AddObject(m, "RTLD_LOCAL", PyLong_FromLong(RTLD_LOCAL));
   5504     PyModule_AddObject(m, "RTLD_GLOBAL", PyLong_FromLong(RTLD_GLOBAL));
   5505 
   5506     PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL);
   5507     if (PyExc_ArgError) {
   5508         Py_INCREF(PyExc_ArgError);
   5509         PyModule_AddObject(m, "ArgumentError", PyExc_ArgError);
   5510     }
   5511     return m;
   5512 }
   5513 
   5514 /*
   5515  Local Variables:
   5516  compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"
   5517  End:
   5518 */
   5519