diff options
author | Antoine Pitrou <solipsis@pitrou.net> | 2010-05-09 16:14:21 (GMT) |
---|---|---|
committer | Antoine Pitrou <solipsis@pitrou.net> | 2010-05-09 16:14:21 (GMT) |
commit | 7f14f0d8a0228c50d5b5de2acbfe9a64ebc6749a (patch) | |
tree | d25489e9531c01f1e9244012bbfaa929f382883e /Modules/_ctypes | |
parent | b7d943625cf4353f6cb72df16252759f2dbd8e06 (diff) | |
download | cpython-7f14f0d8a0228c50d5b5de2acbfe9a64ebc6749a.zip cpython-7f14f0d8a0228c50d5b5de2acbfe9a64ebc6749a.tar.gz cpython-7f14f0d8a0228c50d5b5de2acbfe9a64ebc6749a.tar.bz2 |
Recorded merge of revisions 81032 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/branches/py3k
................
r81032 | antoine.pitrou | 2010-05-09 17:52:27 +0200 (dim., 09 mai 2010) | 9 lines
Recorded merge of revisions 81029 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r81029 | antoine.pitrou | 2010-05-09 16:46:46 +0200 (dim., 09 mai 2010) | 3 lines
Untabify C files. Will watch buildbots.
........
................
Diffstat (limited to 'Modules/_ctypes')
-rw-r--r-- | Modules/_ctypes/_ctypes.c | 8246 | ||||
-rw-r--r-- | Modules/_ctypes/_ctypes_test.c | 452 | ||||
-rw-r--r-- | Modules/_ctypes/callbacks.c | 950 | ||||
-rw-r--r-- | Modules/_ctypes/callproc.c | 2578 | ||||
-rw-r--r-- | Modules/_ctypes/cfield.c | 2106 | ||||
-rw-r--r-- | Modules/_ctypes/ctypes.h | 286 | ||||
-rw-r--r-- | Modules/_ctypes/darwin/dlfcn_simple.c | 282 | ||||
-rw-r--r-- | Modules/_ctypes/malloc_closure.c | 98 | ||||
-rw-r--r-- | Modules/_ctypes/stgdict.c | 942 |
9 files changed, 7970 insertions, 7970 deletions
diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c index 21961ae..c1b3093 100644 --- a/Modules/_ctypes/_ctypes.c +++ b/Modules/_ctypes/_ctypes.c @@ -20,20 +20,20 @@ /* -Name methods, members, getsets +Name methods, members, getsets ============================================================================== -PyCStructType_Type __new__(), from_address(), __mul__(), from_param() -UnionType_Type __new__(), from_address(), __mul__(), from_param() -PyCPointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type() -PyCArrayType_Type __new__(), from_address(), __mul__(), from_param() -PyCSimpleType_Type __new__(), from_address(), __mul__(), from_param() +PyCStructType_Type __new__(), from_address(), __mul__(), from_param() +UnionType_Type __new__(), from_address(), __mul__(), from_param() +PyCPointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type() +PyCArrayType_Type __new__(), from_address(), __mul__(), from_param() +PyCSimpleType_Type __new__(), from_address(), __mul__(), from_param() PyCData_Type - Struct_Type __new__(), __init__() - PyCPointer_Type __new__(), __init__(), _as_parameter_, contents - PyCArray_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__() - Simple_Type __new__(), __init__(), _as_parameter_ + Struct_Type __new__(), __init__() + PyCPointer_Type __new__(), __init__(), _as_parameter_, contents + PyCArray_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__() + Simple_Type __new__(), __init__(), _as_parameter_ PyCField_Type PyCStgDict_Type @@ -45,28 +45,28 @@ class methods It has some similarity to the byref() construct compared to pointer() from_address(addr) - - construct an instance from a given memory block (sharing this memory block) + - construct an instance from a given memory block (sharing this memory block) from_param(obj) - - typecheck and convert a Python object into a C function call parameter - the result may be an instance of the type, or an integer or tuple - (typecode, value[, obj]) + - typecheck and convert a Python object into a C function call parameter + the result may be an instance of the type, or an integer or tuple + (typecode, value[, obj]) instance methods/properties --------------------------- _as_parameter_ - - convert self into a C function call parameter - This is either an integer, or a 3-tuple (typecode, value, obj) + - convert self into a C function call parameter + This is either an integer, or a 3-tuple (typecode, value, obj) functions --------- sizeof(cdata) - - return the number of bytes the buffer contains + - return the number of bytes the buffer contains sizeof(ctype) - - return the number of bytes the buffer of an instance would contain + - return the number of bytes the buffer of an instance would contain byref(cdata) @@ -77,7 +77,7 @@ pointer(cdata) POINTER(ctype) bytes(cdata) - - return the buffer contents as a sequence of bytes (which is currently a string) + - return the buffer contents as a sequence of bytes (which is currently a string) */ @@ -98,7 +98,7 @@ bytes(cdata) * PyCField_Type * */ - + #define PY_SSIZE_T_CLEAN #include "Python.h" @@ -135,128 +135,128 @@ static PyObject *_unpickle; char *_ctypes_conversion_encoding = NULL; char *_ctypes_conversion_errors = NULL; - + /****************************************************************/ typedef struct { - PyObject_HEAD - PyObject *key; - PyObject *dict; + PyObject_HEAD + PyObject *key; + PyObject *dict; } DictRemoverObject; static void _DictRemover_dealloc(PyObject *_self) { - DictRemoverObject *self = (DictRemoverObject *)_self; - Py_XDECREF(self->key); - Py_XDECREF(self->dict); - Py_TYPE(self)->tp_free(_self); + DictRemoverObject *self = (DictRemoverObject *)_self; + Py_XDECREF(self->key); + Py_XDECREF(self->dict); + Py_TYPE(self)->tp_free(_self); } static PyObject * _DictRemover_call(PyObject *_self, PyObject *args, PyObject *kw) { - DictRemoverObject *self = (DictRemoverObject *)_self; - if (self->key && self->dict) { - if (-1 == PyDict_DelItem(self->dict, self->key)) - /* XXX Error context */ - PyErr_WriteUnraisable(Py_None); - Py_DECREF(self->key); - self->key = NULL; - Py_DECREF(self->dict); - self->dict = NULL; - } - Py_INCREF(Py_None); - return Py_None; + DictRemoverObject *self = (DictRemoverObject *)_self; + if (self->key && self->dict) { + if (-1 == PyDict_DelItem(self->dict, self->key)) + /* XXX Error context */ + PyErr_WriteUnraisable(Py_None); + Py_DECREF(self->key); + self->key = NULL; + Py_DECREF(self->dict); + self->dict = NULL; + } + Py_INCREF(Py_None); + return Py_None; } static PyTypeObject DictRemover_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.DictRemover", /* tp_name */ - sizeof(DictRemoverObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - _DictRemover_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - _DictRemover_call, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.DictRemover", /* tp_name */ + sizeof(DictRemoverObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + _DictRemover_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + _DictRemover_call, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ /* XXX should participate in GC? */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - "deletes a key from a dictionary", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + "deletes a key from a dictionary", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; int PyDict_SetItemProxy(PyObject *dict, PyObject *key, PyObject *item) { - PyObject *obj; - DictRemoverObject *remover; - PyObject *proxy; - int result; - - obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL); - if (obj == NULL) - return -1; - - remover = (DictRemoverObject *)obj; - assert(remover->key == NULL); - assert(remover->dict == NULL); - Py_INCREF(key); - remover->key = key; - Py_INCREF(dict); - remover->dict = dict; - - proxy = PyWeakref_NewProxy(item, obj); - Py_DECREF(obj); - if (proxy == NULL) - return -1; - - result = PyDict_SetItem(dict, key, proxy); - Py_DECREF(proxy); - return result; + PyObject *obj; + DictRemoverObject *remover; + PyObject *proxy; + int result; + + obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL); + if (obj == NULL) + return -1; + + remover = (DictRemoverObject *)obj; + assert(remover->key == NULL); + assert(remover->dict == NULL); + Py_INCREF(key); + remover->key = key; + Py_INCREF(dict); + remover->dict = dict; + + proxy = PyWeakref_NewProxy(item, obj); + Py_DECREF(obj); + if (proxy == NULL) + return -1; + + result = PyDict_SetItem(dict, key, proxy); + Py_DECREF(proxy); + return result; } PyObject * PyDict_GetItemProxy(PyObject *dict, PyObject *key) { - PyObject *result; - PyObject *item = PyDict_GetItem(dict, key); - - if (item == NULL) - return NULL; - if (!PyWeakref_CheckProxy(item)) - return item; - result = PyWeakref_GET_OBJECT(item); - if (result == Py_None) - return NULL; - return result; + PyObject *result; + PyObject *item = PyDict_GetItem(dict, key); + + if (item == NULL) + return NULL; + if (!PyWeakref_CheckProxy(item)) + return item; + result = PyWeakref_GET_OBJECT(item); + if (result == Py_None) + return NULL; + return result; } /******************************************************************/ @@ -269,25 +269,25 @@ PyDict_GetItemProxy(PyObject *dict, PyObject *key) char * _ctypes_alloc_format_string(const char *prefix, const char *suffix) { - size_t len; - char *result; - - if (suffix == NULL) { - assert(PyErr_Occurred()); - return NULL; - } - len = strlen(suffix); - if (prefix) - len += strlen(prefix); - result = PyMem_Malloc(len + 1); - if (result == NULL) - return NULL; - if (prefix) - strcpy(result, prefix); - else - result[0] = '\0'; - strcat(result, suffix); - return result; + size_t len; + char *result; + + if (suffix == NULL) { + assert(PyErr_Occurred()); + return NULL; + } + len = strlen(suffix); + if (prefix) + len += strlen(prefix); + result = PyMem_Malloc(len + 1); + if (result == NULL) + return NULL; + if (prefix) + strcpy(result, prefix); + else + result[0] = '\0'; + strcat(result, suffix); + return result; } /* @@ -300,100 +300,100 @@ _ctypes_alloc_format_string(const char *prefix, const char *suffix) static PyCArgObject * StructUnionType_paramfunc(CDataObject *self) { - PyCArgObject *parg; - StgDictObject *stgdict; - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'V'; - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for structure/union instances */ - parg->pffi_type = &stgdict->ffi_type_pointer; - /* For structure parameters (by value), parg->value doesn't contain the structure - data itself, instead parg->value.p *points* to the structure's data - See also _ctypes.c, function _call_function_pointer(). - */ - parg->value.p = self->b_ptr; - parg->size = self->b_size; - Py_INCREF(self); - parg->obj = (PyObject *)self; - return parg; + PyCArgObject *parg; + StgDictObject *stgdict; + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'V'; + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for structure/union instances */ + parg->pffi_type = &stgdict->ffi_type_pointer; + /* For structure parameters (by value), parg->value doesn't contain the structure + data itself, instead parg->value.p *points* to the structure's data + See also _ctypes.c, function _call_function_pointer(). + */ + parg->value.p = self->b_ptr; + parg->size = self->b_size; + Py_INCREF(self); + parg->obj = (PyObject *)self; + return parg; } static PyObject * StructUnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds, int isStruct) { - PyTypeObject *result; - PyObject *fields; - StgDictObject *dict; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (!result) - return NULL; - - /* keep this for bw compatibility */ - if (PyDict_GetItemString(result->tp_dict, "_abstract_")) - return (PyObject *)result; - - dict = (StgDictObject *)PyObject_CallObject((PyObject *)&PyCStgDict_Type, NULL); - if (!dict) { - Py_DECREF(result); - return NULL; - } - /* replace the class dict by our updated stgdict, which holds info - about storage requirements of the instances */ - if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)dict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)dict; - dict->format = _ctypes_alloc_format_string(NULL, "B"); - if (dict->format == NULL) { - Py_DECREF(result); - return NULL; - } - - dict->paramfunc = StructUnionType_paramfunc; - - fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); - if (!fields) { - StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base); - - if (basedict == NULL) - return (PyObject *)result; - /* copy base dict */ - if (-1 == PyCStgDict_clone(dict, basedict)) { - Py_DECREF(result); - return NULL; - } - dict->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass dict */ - basedict->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass dict */ - return (PyObject *)result; - } - - if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) { - Py_DECREF(result); - return NULL; - } - return (PyObject *)result; + PyTypeObject *result; + PyObject *fields; + StgDictObject *dict; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (!result) + return NULL; + + /* keep this for bw compatibility */ + if (PyDict_GetItemString(result->tp_dict, "_abstract_")) + return (PyObject *)result; + + dict = (StgDictObject *)PyObject_CallObject((PyObject *)&PyCStgDict_Type, NULL); + if (!dict) { + Py_DECREF(result); + return NULL; + } + /* replace the class dict by our updated stgdict, which holds info + about storage requirements of the instances */ + if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)dict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)dict; + dict->format = _ctypes_alloc_format_string(NULL, "B"); + if (dict->format == NULL) { + Py_DECREF(result); + return NULL; + } + + dict->paramfunc = StructUnionType_paramfunc; + + fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); + if (!fields) { + StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base); + + if (basedict == NULL) + return (PyObject *)result; + /* copy base dict */ + if (-1 == PyCStgDict_clone(dict, basedict)) { + Py_DECREF(result); + return NULL; + } + dict->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass dict */ + basedict->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass dict */ + return (PyObject *)result; + } + + if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) { + Py_DECREF(result); + return NULL; + } + return (PyObject *)result; } static PyObject * PyCStructType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - return StructUnionType_new(type, args, kwds, 1); + return StructUnionType_new(type, args, kwds, 1); } static PyObject * UnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - return StructUnionType_new(type, args, kwds, 0); + return StructUnionType_new(type, args, kwds, 0); } static char from_address_doc[] = @@ -402,16 +402,16 @@ static char from_address_doc[] = static PyObject * CDataType_from_address(PyObject *type, PyObject *value) { - void *buf; - if (!PyLong_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "integer expected"); - return NULL; - } - buf = (void *)PyLong_AsVoidPtr(value); - if (PyErr_Occurred()) - return NULL; - return PyCData_AtAddress(type, buf); + void *buf; + if (!PyLong_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "integer expected"); + return NULL; + } + buf = (void *)PyLong_AsVoidPtr(value); + if (PyErr_Occurred()) + return NULL; + return PyCData_AtAddress(type, buf); } static char from_buffer_doc[] = @@ -423,51 +423,51 @@ KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep); static PyObject * CDataType_from_buffer(PyObject *type, PyObject *args) { - void *buffer; - Py_ssize_t buffer_len; - Py_ssize_t offset = 0; - PyObject *obj, *result; - StgDictObject *dict = PyType_stgdict(type); - assert (dict); - - if (!PyArg_ParseTuple(args, + void *buffer; + Py_ssize_t buffer_len; + Py_ssize_t offset = 0; + PyObject *obj, *result; + StgDictObject *dict = PyType_stgdict(type); + assert (dict); + + if (!PyArg_ParseTuple(args, #if (PY_VERSION_HEX < 0x02050000) - "O|i:from_buffer", + "O|i:from_buffer", #else - "O|n:from_buffer", + "O|n:from_buffer", #endif - &obj, &offset)) - return NULL; - - if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len)) - return NULL; - - if (offset < 0) { - PyErr_SetString(PyExc_ValueError, - "offset cannot be negative"); - return NULL; - } - if (dict->size > buffer_len - offset) { - PyErr_Format(PyExc_ValueError, + &obj, &offset)) + return NULL; + + if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len)) + return NULL; + + if (offset < 0) { + PyErr_SetString(PyExc_ValueError, + "offset cannot be negative"); + return NULL; + } + if (dict->size > buffer_len - offset) { + PyErr_Format(PyExc_ValueError, #if (PY_VERSION_HEX < 0x02050000) - "Buffer size too small (%d instead of at least %d bytes)", + "Buffer size too small (%d instead of at least %d bytes)", #else - "Buffer size too small (%zd instead of at least %zd bytes)", + "Buffer size too small (%zd instead of at least %zd bytes)", #endif - buffer_len, dict->size + offset); - return NULL; - } - - result = PyCData_AtAddress(type, (char *)buffer + offset); - if (result == NULL) - return NULL; - - Py_INCREF(obj); - if (-1 == KeepRef((CDataObject *)result, -1, obj)) { - Py_DECREF(result); - return NULL; - } - return result; + buffer_len, dict->size + offset); + return NULL; + } + + result = PyCData_AtAddress(type, (char *)buffer + offset); + if (result == NULL) + return NULL; + + Py_INCREF(obj); + if (-1 == KeepRef((CDataObject *)result, -1, obj)) { + Py_DECREF(result); + return NULL; + } + return result; } static char from_buffer_copy_doc[] = @@ -479,48 +479,48 @@ GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static PyObject * CDataType_from_buffer_copy(PyObject *type, PyObject *args) { - const void *buffer; - Py_ssize_t buffer_len; - Py_ssize_t offset = 0; - PyObject *obj, *result; - StgDictObject *dict = PyType_stgdict(type); - assert (dict); - - if (!PyArg_ParseTuple(args, + const void *buffer; + Py_ssize_t buffer_len; + Py_ssize_t offset = 0; + PyObject *obj, *result; + StgDictObject *dict = PyType_stgdict(type); + assert (dict); + + if (!PyArg_ParseTuple(args, #if (PY_VERSION_HEX < 0x02050000) - "O|i:from_buffer", + "O|i:from_buffer", #else - "O|n:from_buffer", + "O|n:from_buffer", #endif - &obj, &offset)) - return NULL; + &obj, &offset)) + return NULL; - if (-1 == PyObject_AsReadBuffer(obj, (const void**)&buffer, &buffer_len)) - return NULL; + if (-1 == PyObject_AsReadBuffer(obj, (const void**)&buffer, &buffer_len)) + return NULL; - if (offset < 0) { - PyErr_SetString(PyExc_ValueError, - "offset cannot be negative"); - return NULL; - } + if (offset < 0) { + PyErr_SetString(PyExc_ValueError, + "offset cannot be negative"); + return NULL; + } - if (dict->size > buffer_len - offset) { - PyErr_Format(PyExc_ValueError, + if (dict->size > buffer_len - offset) { + PyErr_Format(PyExc_ValueError, #if (PY_VERSION_HEX < 0x02050000) - "Buffer size too small (%d instead of at least %d bytes)", + "Buffer size too small (%d instead of at least %d bytes)", #else - "Buffer size too small (%zd instead of at least %zd bytes)", + "Buffer size too small (%zd instead of at least %zd bytes)", #endif - buffer_len, dict->size + offset); - return NULL; - } - - result = GenericPyCData_new((PyTypeObject *)type, NULL, NULL); - if (result == NULL) - return NULL; - memcpy(((CDataObject *)result)->b_ptr, - (char *)buffer+offset, dict->size); - return result; + buffer_len, dict->size + offset); + return NULL; + } + + result = GenericPyCData_new((PyTypeObject *)type, NULL, NULL); + if (result == NULL) + return NULL; + memcpy(((CDataObject *)result)->b_ptr, + (char *)buffer+offset, dict->size); + return result; } static char in_dll_doc[] = @@ -529,55 +529,55 @@ static char in_dll_doc[] = static PyObject * CDataType_in_dll(PyObject *type, PyObject *args) { - PyObject *dll; - char *name; - PyObject *obj; - void *handle; - void *address; - - if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name)) - return NULL; - - obj = PyObject_GetAttrString(dll, "_handle"); - if (!obj) - return NULL; - if (!PyLong_Check(obj)) { - PyErr_SetString(PyExc_TypeError, - "the _handle attribute of the second argument must be an integer"); - Py_DECREF(obj); - return NULL; - } - handle = (void *)PyLong_AsVoidPtr(obj); - Py_DECREF(obj); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_ValueError, - "could not convert the _handle attribute to a pointer"); - return NULL; - } + PyObject *dll; + char *name; + PyObject *obj; + void *handle; + void *address; + + if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name)) + return NULL; + + obj = PyObject_GetAttrString(dll, "_handle"); + if (!obj) + return NULL; + if (!PyLong_Check(obj)) { + PyErr_SetString(PyExc_TypeError, + "the _handle attribute of the second argument must be an integer"); + Py_DECREF(obj); + return NULL; + } + handle = (void *)PyLong_AsVoidPtr(obj); + Py_DECREF(obj); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "could not convert the _handle attribute to a pointer"); + return NULL; + } #ifdef MS_WIN32 - address = (void *)GetProcAddress(handle, name); - if (!address) { - PyErr_Format(PyExc_ValueError, - "symbol '%s' not found", - name); - return NULL; - } + address = (void *)GetProcAddress(handle, name); + if (!address) { + PyErr_Format(PyExc_ValueError, + "symbol '%s' not found", + name); + return NULL; + } #else - address = (void *)ctypes_dlsym(handle, name); - if (!address) { + address = (void *)ctypes_dlsym(handle, name); + if (!address) { #ifdef __CYGWIN__ /* dlerror() isn't very helpful on cygwin */ - PyErr_Format(PyExc_ValueError, - "symbol '%s' not found (%s) ", - name); + PyErr_Format(PyExc_ValueError, + "symbol '%s' not found (%s) ", + name); #else - PyErr_SetString(PyExc_ValueError, ctypes_dlerror()); + PyErr_SetString(PyExc_ValueError, ctypes_dlerror()); #endif - return NULL; - } + return NULL; + } #endif - return PyCData_AtAddress(type, address); + return PyCData_AtAddress(type, address); } static char from_param_doc[] = @@ -586,210 +586,210 @@ static char from_param_doc[] = static PyObject * CDataType_from_param(PyObject *type, PyObject *value) { - PyObject *as_parameter; - if (1 == PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - if (PyCArg_CheckExact(value)) { - PyCArgObject *p = (PyCArgObject *)value; - PyObject *ob = p->obj; - const char *ob_name; - StgDictObject *dict; - dict = PyType_stgdict(type); - - /* If we got a PyCArgObject, we must check if the object packed in it - is an instance of the type's dict->proto */ - if(dict && ob - && PyObject_IsInstance(ob, dict->proto)) { - Py_INCREF(value); - return value; - } - ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???"; - PyErr_Format(PyExc_TypeError, - "expected %s instance instead of pointer to %s", - ((PyTypeObject *)type)->tp_name, ob_name); - return NULL; - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = CDataType_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - PyErr_Format(PyExc_TypeError, - "expected %s instance instead of %s", - ((PyTypeObject *)type)->tp_name, - Py_TYPE(value)->tp_name); - return NULL; + PyObject *as_parameter; + if (1 == PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + if (PyCArg_CheckExact(value)) { + PyCArgObject *p = (PyCArgObject *)value; + PyObject *ob = p->obj; + const char *ob_name; + StgDictObject *dict; + dict = PyType_stgdict(type); + + /* If we got a PyCArgObject, we must check if the object packed in it + is an instance of the type's dict->proto */ + if(dict && ob + && PyObject_IsInstance(ob, dict->proto)) { + Py_INCREF(value); + return value; + } + ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???"; + PyErr_Format(PyExc_TypeError, + "expected %s instance instead of pointer to %s", + ((PyTypeObject *)type)->tp_name, ob_name); + return NULL; + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = CDataType_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + PyErr_Format(PyExc_TypeError, + "expected %s instance instead of %s", + ((PyTypeObject *)type)->tp_name, + Py_TYPE(value)->tp_name); + return NULL; } static PyMethodDef CDataType_methods[] = { - { "from_param", CDataType_from_param, METH_O, from_param_doc }, - { "from_address", CDataType_from_address, METH_O, from_address_doc }, - { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, - { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, - { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc }, - { NULL, NULL }, + { "from_param", CDataType_from_param, METH_O, from_param_doc }, + { "from_address", CDataType_from_address, METH_O, from_address_doc }, + { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, + { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, + { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc }, + { NULL, NULL }, }; static PyObject * CDataType_repeat(PyObject *self, Py_ssize_t length) { - if (length < 0) - return PyErr_Format(PyExc_ValueError, - "Array length must be >= 0, not %zd", - length); - return PyCArrayType_from_ctype(self, length); + if (length < 0) + return PyErr_Format(PyExc_ValueError, + "Array length must be >= 0, not %zd", + length); + return PyCArrayType_from_ctype(self, length); } static PySequenceMethods CDataType_as_sequence = { - 0, /* inquiry sq_length; */ - 0, /* binaryfunc sq_concat; */ - CDataType_repeat, /* intargfunc sq_repeat; */ - 0, /* intargfunc sq_item; */ - 0, /* intintargfunc sq_slice; */ - 0, /* intobjargproc sq_ass_item; */ - 0, /* intintobjargproc sq_ass_slice; */ - 0, /* objobjproc sq_contains; */ - - 0, /* binaryfunc sq_inplace_concat; */ - 0, /* intargfunc sq_inplace_repeat; */ + 0, /* inquiry sq_length; */ + 0, /* binaryfunc sq_concat; */ + CDataType_repeat, /* intargfunc sq_repeat; */ + 0, /* intargfunc sq_item; */ + 0, /* intintargfunc sq_slice; */ + 0, /* intobjargproc sq_ass_item; */ + 0, /* intintobjargproc sq_ass_slice; */ + 0, /* objobjproc sq_contains; */ + + 0, /* binaryfunc sq_inplace_concat; */ + 0, /* intargfunc sq_inplace_repeat; */ }; static int CDataType_clear(PyTypeObject *self) { - StgDictObject *dict = PyType_stgdict((PyObject *)self); - if (dict) - Py_CLEAR(dict->proto); - return PyType_Type.tp_clear((PyObject *)self); + StgDictObject *dict = PyType_stgdict((PyObject *)self); + if (dict) + Py_CLEAR(dict->proto); + return PyType_Type.tp_clear((PyObject *)self); } static int CDataType_traverse(PyTypeObject *self, visitproc visit, void *arg) { - StgDictObject *dict = PyType_stgdict((PyObject *)self); - if (dict) - Py_VISIT(dict->proto); - return PyType_Type.tp_traverse((PyObject *)self, visit, arg); + StgDictObject *dict = PyType_stgdict((PyObject *)self); + if (dict) + Py_VISIT(dict->proto); + return PyType_Type.tp_traverse((PyObject *)self, visit, arg); } static int PyCStructType_setattro(PyObject *self, PyObject *key, PyObject *value) { - /* XXX Should we disallow deleting _fields_? */ - if (-1 == PyType_Type.tp_setattro(self, key, value)) - return -1; - - if (value && PyUnicode_Check(key) && - /* XXX struni _PyUnicode_AsString can fail (also in other places)! */ - 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) - return PyCStructUnionType_update_stgdict(self, value, 1); - return 0; + /* XXX Should we disallow deleting _fields_? */ + if (-1 == PyType_Type.tp_setattro(self, key, value)) + return -1; + + if (value && PyUnicode_Check(key) && + /* XXX struni _PyUnicode_AsString can fail (also in other places)! */ + 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) + return PyCStructUnionType_update_stgdict(self, value, 1); + return 0; } static int UnionType_setattro(PyObject *self, PyObject *key, PyObject *value) { - /* XXX Should we disallow deleting _fields_? */ - if (-1 == PyObject_GenericSetAttr(self, key, value)) - return -1; - - if (PyUnicode_Check(key) && - 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) - return PyCStructUnionType_update_stgdict(self, value, 0); - return 0; + /* XXX Should we disallow deleting _fields_? */ + if (-1 == PyObject_GenericSetAttr(self, key, value)) + return -1; + + if (PyUnicode_Check(key) && + 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) + return PyCStructUnionType_update_stgdict(self, value, 0); + return 0; } PyTypeObject PyCStructType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCStructType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - PyCStructType_setattro, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for the CData Objects", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCStructType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCStructType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + PyCStructType_setattro, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for the CData Objects", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCStructType_new, /* tp_new */ + 0, /* tp_free */ }; static PyTypeObject UnionType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.UnionType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - UnionType_setattro, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for the CData Objects", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - UnionType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.UnionType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + UnionType_setattro, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for the CData Objects", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + UnionType_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* @@ -809,124 +809,124 @@ size property/method, and the sequence protocol. static int PyCPointerType_SetProto(StgDictObject *stgdict, PyObject *proto) { - if (!proto || !PyType_Check(proto)) { - PyErr_SetString(PyExc_TypeError, - "_type_ must be a type"); - return -1; - } - if (!PyType_stgdict(proto)) { - PyErr_SetString(PyExc_TypeError, - "_type_ must have storage info"); - return -1; - } - Py_INCREF(proto); - Py_XDECREF(stgdict->proto); - stgdict->proto = proto; - return 0; + if (!proto || !PyType_Check(proto)) { + PyErr_SetString(PyExc_TypeError, + "_type_ must be a type"); + return -1; + } + if (!PyType_stgdict(proto)) { + PyErr_SetString(PyExc_TypeError, + "_type_ must have storage info"); + return -1; + } + Py_INCREF(proto); + Py_XDECREF(stgdict->proto); + stgdict->proto = proto; + return 0; } static PyCArgObject * PyCPointerType_paramfunc(CDataObject *self) { - PyCArgObject *parg; - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - Py_INCREF(self); - parg->obj = (PyObject *)self; - parg->value.p = *(void **)self->b_ptr; - return parg; + PyCArgObject *parg; + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + Py_INCREF(self); + parg->obj = (PyObject *)self; + parg->value.p = *(void **)self->b_ptr; + return parg; } static PyObject * PyCPointerType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; - PyObject *proto; - PyObject *typedict; - - typedict = PyTuple_GetItem(args, 2); - if (!typedict) - return NULL; + PyTypeObject *result; + StgDictObject *stgdict; + PyObject *proto; + PyObject *typedict; + + typedict = PyTuple_GetItem(args, 2); + if (!typedict) + return NULL; /* stgdict items size, align, length contain info about pointers itself, stgdict->proto has info about the pointed to type! */ - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - return NULL; - stgdict->size = sizeof(void *); - stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; - stgdict->length = 1; - stgdict->ffi_type_pointer = ffi_type_pointer; - stgdict->paramfunc = PyCPointerType_paramfunc; - stgdict->flags |= TYPEFLAG_ISPOINTER; - - proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ - if (proto && -1 == PyCPointerType_SetProto(stgdict, proto)) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - if (proto) { - StgDictObject *itemdict = PyType_stgdict(proto); - assert(itemdict); - /* If itemdict->format is NULL, then this is a pointer to an - incomplete type. We create a generic format string - 'pointer to bytes' in this case. XXX Better would be to - fix the format string later... - */ - stgdict->format = _ctypes_alloc_format_string("&", - itemdict->format ? itemdict->format : "B"); - if (stgdict->format == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - } - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; - - return (PyObject *)result; + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + return NULL; + stgdict->size = sizeof(void *); + stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; + stgdict->length = 1; + stgdict->ffi_type_pointer = ffi_type_pointer; + stgdict->paramfunc = PyCPointerType_paramfunc; + stgdict->flags |= TYPEFLAG_ISPOINTER; + + proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ + if (proto && -1 == PyCPointerType_SetProto(stgdict, proto)) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + if (proto) { + StgDictObject *itemdict = PyType_stgdict(proto); + assert(itemdict); + /* If itemdict->format is NULL, then this is a pointer to an + incomplete type. We create a generic format string + 'pointer to bytes' in this case. XXX Better would be to + fix the format string later... + */ + stgdict->format = _ctypes_alloc_format_string("&", + itemdict->format ? itemdict->format : "B"); + if (stgdict->format == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + } + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + + return (PyObject *)result; } static PyObject * PyCPointerType_set_type(PyTypeObject *self, PyObject *type) { - StgDictObject *dict; + StgDictObject *dict; - dict = PyType_stgdict((PyObject *)self); - assert(dict); + dict = PyType_stgdict((PyObject *)self); + assert(dict); - if (-1 == PyCPointerType_SetProto(dict, type)) - return NULL; + if (-1 == PyCPointerType_SetProto(dict, type)) + return NULL; - if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type)) - return NULL; + if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type)) + return NULL; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject *_byref(PyObject *); @@ -934,98 +934,98 @@ static PyObject *_byref(PyObject *); static PyObject * PyCPointerType_from_param(PyObject *type, PyObject *value) { - StgDictObject *typedict; - - if (value == Py_None) { - /* ConvParam will convert to a NULL pointer later */ - Py_INCREF(value); - return value; - } - - typedict = PyType_stgdict(type); - assert(typedict); /* Cannot be NULL for pointer types */ - - /* If we expect POINTER(<type>), but receive a <type> instance, accept - it by calling byref(<type>). - */ - switch (PyObject_IsInstance(value, typedict->proto)) { - case 1: - Py_INCREF(value); /* _byref steals a refcount */ - return _byref(value); - case -1: - PyErr_Clear(); - break; - default: - break; - } - - if (PointerObject_Check(value) || ArrayObject_Check(value)) { - /* Array instances are also pointers when - the item types are the same. - */ - StgDictObject *v = PyObject_stgdict(value); - assert(v); /* Cannot be NULL for pointer or array objects */ - if (PyObject_IsSubclass(v->proto, typedict->proto)) { - Py_INCREF(value); - return value; - } - } - return CDataType_from_param(type, value); + StgDictObject *typedict; + + if (value == Py_None) { + /* ConvParam will convert to a NULL pointer later */ + Py_INCREF(value); + return value; + } + + typedict = PyType_stgdict(type); + assert(typedict); /* Cannot be NULL for pointer types */ + + /* If we expect POINTER(<type>), but receive a <type> instance, accept + it by calling byref(<type>). + */ + switch (PyObject_IsInstance(value, typedict->proto)) { + case 1: + Py_INCREF(value); /* _byref steals a refcount */ + return _byref(value); + case -1: + PyErr_Clear(); + break; + default: + break; + } + + if (PointerObject_Check(value) || ArrayObject_Check(value)) { + /* Array instances are also pointers when + the item types are the same. + */ + StgDictObject *v = PyObject_stgdict(value); + assert(v); /* Cannot be NULL for pointer or array objects */ + if (PyObject_IsSubclass(v->proto, typedict->proto)) { + Py_INCREF(value); + return value; + } + } + return CDataType_from_param(type, value); } static PyMethodDef PyCPointerType_methods[] = { - { "from_address", CDataType_from_address, METH_O, from_address_doc }, - { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, - { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, - { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, - { "from_param", (PyCFunction)PyCPointerType_from_param, METH_O, from_param_doc}, - { "set_type", (PyCFunction)PyCPointerType_set_type, METH_O }, - { NULL, NULL }, + { "from_address", CDataType_from_address, METH_O, from_address_doc }, + { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, + { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, + { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, + { "from_param", (PyCFunction)PyCPointerType_from_param, METH_O, from_param_doc}, + { "set_type", (PyCFunction)PyCPointerType_set_type, METH_O }, + { NULL, NULL }, }; PyTypeObject PyCPointerType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCPointerType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for the Pointer Objects", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PyCPointerType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCPointerType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCPointerType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for the Pointer Objects", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PyCPointerType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCPointerType_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCArrayType_Type @@ -1038,152 +1038,152 @@ PyTypeObject PyCPointerType_Type = { static int CharArray_set_raw(CDataObject *self, PyObject *value) { - char *ptr; - Py_ssize_t size; - Py_buffer view; - - if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) - return -1; - size = view.len; - ptr = view.buf; - if (size > self->b_size) { - PyErr_SetString(PyExc_ValueError, - "string too long"); - goto fail; - } - - memcpy(self->b_ptr, ptr, size); - - PyBuffer_Release(&view); - return 0; - fail: - PyBuffer_Release(&view); + char *ptr; + Py_ssize_t size; + Py_buffer view; + + if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) return -1; + size = view.len; + ptr = view.buf; + if (size > self->b_size) { + PyErr_SetString(PyExc_ValueError, + "string too long"); + goto fail; + } + + memcpy(self->b_ptr, ptr, size); + + PyBuffer_Release(&view); + return 0; + fail: + PyBuffer_Release(&view); + return -1; } static PyObject * CharArray_get_raw(CDataObject *self) { - return PyBytes_FromStringAndSize(self->b_ptr, self->b_size); + return PyBytes_FromStringAndSize(self->b_ptr, self->b_size); } static PyObject * CharArray_get_value(CDataObject *self) { - int i; - char *ptr = self->b_ptr; - for (i = 0; i < self->b_size; ++i) - if (*ptr++ == '\0') - break; - return PyBytes_FromStringAndSize(self->b_ptr, i); + int i; + char *ptr = self->b_ptr; + for (i = 0; i < self->b_size; ++i) + if (*ptr++ == '\0') + break; + return PyBytes_FromStringAndSize(self->b_ptr, i); } static int CharArray_set_value(CDataObject *self, PyObject *value) { - char *ptr; - Py_ssize_t size; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - - if (PyUnicode_Check(value)) { - value = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return -1; - } else if (!PyBytes_Check(value)) { - PyErr_Format(PyExc_TypeError, - "str/bytes expected instead of %s instance", - Py_TYPE(value)->tp_name); - return -1; - } else - Py_INCREF(value); - size = PyBytes_GET_SIZE(value); - if (size > self->b_size) { - PyErr_SetString(PyExc_ValueError, - "string too long"); - Py_DECREF(value); - return -1; - } - - ptr = PyBytes_AS_STRING(value); - memcpy(self->b_ptr, ptr, size); - if (size < self->b_size) - self->b_ptr[size] = '\0'; - Py_DECREF(value); - - return 0; + char *ptr; + Py_ssize_t size; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } + + if (PyUnicode_Check(value)) { + value = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return -1; + } else if (!PyBytes_Check(value)) { + PyErr_Format(PyExc_TypeError, + "str/bytes expected instead of %s instance", + Py_TYPE(value)->tp_name); + return -1; + } else + Py_INCREF(value); + size = PyBytes_GET_SIZE(value); + if (size > self->b_size) { + PyErr_SetString(PyExc_ValueError, + "string too long"); + Py_DECREF(value); + return -1; + } + + ptr = PyBytes_AS_STRING(value); + memcpy(self->b_ptr, ptr, size); + if (size < self->b_size) + self->b_ptr[size] = '\0'; + Py_DECREF(value); + + return 0; } static PyGetSetDef CharArray_getsets[] = { - { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw, - "value", NULL }, - { "value", (getter)CharArray_get_value, (setter)CharArray_set_value, - "string value"}, - { NULL, NULL } + { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw, + "value", NULL }, + { "value", (getter)CharArray_get_value, (setter)CharArray_set_value, + "string value"}, + { NULL, NULL } }; #ifdef CTYPES_UNICODE static PyObject * WCharArray_get_value(CDataObject *self) { - unsigned int i; - wchar_t *ptr = (wchar_t *)self->b_ptr; - for (i = 0; i < self->b_size/sizeof(wchar_t); ++i) - if (*ptr++ == (wchar_t)0) - break; - return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i); + unsigned int i; + wchar_t *ptr = (wchar_t *)self->b_ptr; + for (i = 0; i < self->b_size/sizeof(wchar_t); ++i) + if (*ptr++ == (wchar_t)0) + break; + return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i); } static int WCharArray_set_value(CDataObject *self, PyObject *value) { - Py_ssize_t result = 0; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return -1; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - Py_TYPE(value)->tp_name); - return -1; - } else - Py_INCREF(value); - if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) { - PyErr_SetString(PyExc_ValueError, - "string too long"); - result = -1; - goto done; - } - result = PyUnicode_AsWideChar((PyUnicodeObject *)value, - (wchar_t *)self->b_ptr, - self->b_size/sizeof(wchar_t)); - if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t)) - ((wchar_t *)self->b_ptr)[result] = (wchar_t)0; + Py_ssize_t result = 0; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return -1; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + Py_TYPE(value)->tp_name); + return -1; + } else + Py_INCREF(value); + if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) { + PyErr_SetString(PyExc_ValueError, + "string too long"); + result = -1; + goto done; + } + result = PyUnicode_AsWideChar((PyUnicodeObject *)value, + (wchar_t *)self->b_ptr, + self->b_size/sizeof(wchar_t)); + if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t)) + ((wchar_t *)self->b_ptr)[result] = (wchar_t)0; done: - Py_DECREF(value); + Py_DECREF(value); - return result >= 0 ? 0 : -1; + return result >= 0 ? 0 : -1; } static PyGetSetDef WCharArray_getsets[] = { - { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value, - "string value"}, - { NULL, NULL } + { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value, + "string value"}, + { NULL, NULL } }; #endif @@ -1198,236 +1198,236 @@ static PyGetSetDef WCharArray_getsets[] = { static int add_methods(PyTypeObject *type, PyMethodDef *meth) { - PyObject *dict = type->tp_dict; - for (; meth->ml_name != NULL; meth++) { - PyObject *descr; - descr = PyDescr_NewMethod(type, meth); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + PyObject *dict = type->tp_dict; + for (; meth->ml_name != NULL; meth++) { + PyObject *descr; + descr = PyDescr_NewMethod(type, meth); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static int add_members(PyTypeObject *type, PyMemberDef *memb) { - PyObject *dict = type->tp_dict; - for (; memb->name != NULL; memb++) { - PyObject *descr; - descr = PyDescr_NewMember(type, memb); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, memb->name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + PyObject *dict = type->tp_dict; + for (; memb->name != NULL; memb++) { + PyObject *descr; + descr = PyDescr_NewMember(type, memb); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, memb->name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } */ static int add_getset(PyTypeObject *type, PyGetSetDef *gsp) { - PyObject *dict = type->tp_dict; - for (; gsp->name != NULL; gsp++) { - PyObject *descr; - descr = PyDescr_NewGetSet(type, gsp); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, gsp->name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + PyObject *dict = type->tp_dict; + for (; gsp->name != NULL; gsp++) { + PyObject *descr; + descr = PyDescr_NewGetSet(type, gsp); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, gsp->name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static PyCArgObject * PyCArrayType_paramfunc(CDataObject *self) { - PyCArgObject *p = PyCArgObject_new(); - if (p == NULL) - return NULL; - p->tag = 'P'; - p->pffi_type = &ffi_type_pointer; - p->value.p = (char *)self->b_ptr; - Py_INCREF(self); - p->obj = (PyObject *)self; - return p; + PyCArgObject *p = PyCArgObject_new(); + if (p == NULL) + return NULL; + p->tag = 'P'; + p->pffi_type = &ffi_type_pointer; + p->value.p = (char *)self->b_ptr; + Py_INCREF(self); + p->obj = (PyObject *)self; + return p; } static PyObject * PyCArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; - StgDictObject *itemdict; - PyObject *proto; - PyObject *typedict; - long length; - int overflow; - Py_ssize_t itemsize, itemalign; - char buf[32]; - - typedict = PyTuple_GetItem(args, 2); - if (!typedict) - return NULL; - - proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */ - if (!proto || !PyLong_Check(proto)) { - PyErr_SetString(PyExc_AttributeError, - "class must define a '_length_' attribute, " - "which must be a positive integer"); - return NULL; - } - length = PyLong_AsLongAndOverflow(proto, &overflow); - if (overflow) { - PyErr_SetString(PyExc_OverflowError, - "The '_length_' attribute is too large"); - return NULL; - } - - proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ - if (!proto) { - PyErr_SetString(PyExc_AttributeError, - "class must define a '_type_' attribute"); - return NULL; - } - - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - return NULL; - - itemdict = PyType_stgdict(proto); - if (!itemdict) { - PyErr_SetString(PyExc_TypeError, - "_type_ must have storage info"); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - assert(itemdict->format); - if (itemdict->format[0] == '(') { - sprintf(buf, "(%ld,", length); - stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format+1); - } else { - sprintf(buf, "(%ld)", length); - stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format); - } - if (stgdict->format == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - stgdict->ndim = itemdict->ndim + 1; - stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim); - if (stgdict->shape == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - stgdict->shape[0] = length; - memmove(&stgdict->shape[1], itemdict->shape, - sizeof(Py_ssize_t) * (stgdict->ndim - 1)); - - itemsize = itemdict->size; - if (length * itemsize < 0) { - PyErr_SetString(PyExc_OverflowError, - "array too large"); - return NULL; - } - - itemalign = itemdict->align; - - if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) - stgdict->flags |= TYPEFLAG_HASPOINTER; - - stgdict->size = itemsize * length; - stgdict->align = itemalign; - stgdict->length = length; - Py_INCREF(proto); - stgdict->proto = proto; - - stgdict->paramfunc = &PyCArrayType_paramfunc; - - /* Arrays are passed as pointers to function calls. */ - stgdict->ffi_type_pointer = ffi_type_pointer; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) - return NULL; - - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; - - /* Special case for character arrays. - A permanent annoyance: char arrays are also strings! - */ - if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - if (-1 == add_getset(result, CharArray_getsets)) - return NULL; + PyTypeObject *result; + StgDictObject *stgdict; + StgDictObject *itemdict; + PyObject *proto; + PyObject *typedict; + long length; + int overflow; + Py_ssize_t itemsize, itemalign; + char buf[32]; + + typedict = PyTuple_GetItem(args, 2); + if (!typedict) + return NULL; + + proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */ + if (!proto || !PyLong_Check(proto)) { + PyErr_SetString(PyExc_AttributeError, + "class must define a '_length_' attribute, " + "which must be a positive integer"); + return NULL; + } + length = PyLong_AsLongAndOverflow(proto, &overflow); + if (overflow) { + PyErr_SetString(PyExc_OverflowError, + "The '_length_' attribute is too large"); + return NULL; + } + + proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ + if (!proto) { + PyErr_SetString(PyExc_AttributeError, + "class must define a '_type_' attribute"); + return NULL; + } + + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + return NULL; + + itemdict = PyType_stgdict(proto); + if (!itemdict) { + PyErr_SetString(PyExc_TypeError, + "_type_ must have storage info"); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + assert(itemdict->format); + if (itemdict->format[0] == '(') { + sprintf(buf, "(%ld,", length); + stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format+1); + } else { + sprintf(buf, "(%ld)", length); + stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format); + } + if (stgdict->format == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + stgdict->ndim = itemdict->ndim + 1; + stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim); + if (stgdict->shape == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + stgdict->shape[0] = length; + memmove(&stgdict->shape[1], itemdict->shape, + sizeof(Py_ssize_t) * (stgdict->ndim - 1)); + + itemsize = itemdict->size; + if (length * itemsize < 0) { + PyErr_SetString(PyExc_OverflowError, + "array too large"); + return NULL; + } + + itemalign = itemdict->align; + + if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) + stgdict->flags |= TYPEFLAG_HASPOINTER; + + stgdict->size = itemsize * length; + stgdict->align = itemalign; + stgdict->length = length; + Py_INCREF(proto); + stgdict->proto = proto; + + stgdict->paramfunc = &PyCArrayType_paramfunc; + + /* Arrays are passed as pointers to function calls. */ + stgdict->ffi_type_pointer = ffi_type_pointer; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) + return NULL; + + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + + /* Special case for character arrays. + A permanent annoyance: char arrays are also strings! + */ + if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + if (-1 == add_getset(result, CharArray_getsets)) + return NULL; #ifdef CTYPES_UNICODE - } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - if (-1 == add_getset(result, WCharArray_getsets)) - return NULL; + } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + if (-1 == add_getset(result, WCharArray_getsets)) + return NULL; #endif - } + } - return (PyObject *)result; + return (PyObject *)result; } PyTypeObject PyCArrayType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCArrayType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "metatype for the Array Objects", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCArrayType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCArrayType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "metatype for the Array Objects", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCArrayType_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCSimpleType_Type @@ -1444,273 +1444,273 @@ static char *SIMPLE_TYPE_CHARS = "cbBhHiIlLdfuzZqQPXOv?g"; static PyObject * c_wchar_p_from_param(PyObject *type, PyObject *value) { - PyObject *as_parameter; - if (value == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - if (PyUnicode_Check(value) || PyBytes_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("Z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'Z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } - if (PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - if (ArrayObject_Check(value) || PointerObject_Check(value)) { - /* c_wchar array instance or pointer(c_wchar(...)) */ - StgDictObject *dt = PyObject_stgdict(value); - StgDictObject *dict; - assert(dt); /* Cannot be NULL for pointer or array objects */ - dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; - if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { - Py_INCREF(value); - return value; - } - } - if (PyCArg_CheckExact(value)) { - /* byref(c_char(...)) */ - PyCArgObject *a = (PyCArgObject *)value; - StgDictObject *dict = PyObject_stgdict(a->obj); - if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { - Py_INCREF(value); - return value; - } - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = c_wchar_p_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - /* XXX better message */ - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + PyObject *as_parameter; + if (value == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + if (PyUnicode_Check(value) || PyBytes_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("Z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'Z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } + if (PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + if (ArrayObject_Check(value) || PointerObject_Check(value)) { + /* c_wchar array instance or pointer(c_wchar(...)) */ + StgDictObject *dt = PyObject_stgdict(value); + StgDictObject *dict; + assert(dt); /* Cannot be NULL for pointer or array objects */ + dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; + if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { + Py_INCREF(value); + return value; + } + } + if (PyCArg_CheckExact(value)) { + /* byref(c_char(...)) */ + PyCArgObject *a = (PyCArgObject *)value; + StgDictObject *dict = PyObject_stgdict(a->obj); + if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { + Py_INCREF(value); + return value; + } + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = c_wchar_p_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + /* XXX better message */ + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyObject * c_char_p_from_param(PyObject *type, PyObject *value) { - PyObject *as_parameter; - if (value == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - if (PyBytes_Check(value) || PyUnicode_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } - if (PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - if (ArrayObject_Check(value) || PointerObject_Check(value)) { - /* c_char array instance or pointer(c_char(...)) */ - StgDictObject *dt = PyObject_stgdict(value); - StgDictObject *dict; - assert(dt); /* Cannot be NULL for pointer or array objects */ - dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; - if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { - Py_INCREF(value); - return value; - } - } - if (PyCArg_CheckExact(value)) { - /* byref(c_char(...)) */ - PyCArgObject *a = (PyCArgObject *)value; - StgDictObject *dict = PyObject_stgdict(a->obj); - if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { - Py_INCREF(value); - return value; - } - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = c_char_p_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - /* XXX better message */ - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + PyObject *as_parameter; + if (value == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + if (PyBytes_Check(value) || PyUnicode_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } + if (PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + if (ArrayObject_Check(value) || PointerObject_Check(value)) { + /* c_char array instance or pointer(c_char(...)) */ + StgDictObject *dt = PyObject_stgdict(value); + StgDictObject *dict; + assert(dt); /* Cannot be NULL for pointer or array objects */ + dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; + if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { + Py_INCREF(value); + return value; + } + } + if (PyCArg_CheckExact(value)) { + /* byref(c_char(...)) */ + PyCArgObject *a = (PyCArgObject *)value; + StgDictObject *dict = PyObject_stgdict(a->obj); + if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { + Py_INCREF(value); + return value; + } + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = c_char_p_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + /* XXX better message */ + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyObject * c_void_p_from_param(PyObject *type, PyObject *value) { - StgDictObject *stgd; - PyObject *as_parameter; + StgDictObject *stgd; + PyObject *as_parameter; /* None */ - if (value == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - /* Should probably allow buffer interface as well */ + if (value == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + /* Should probably allow buffer interface as well */ /* int, long */ - if (PyLong_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("P"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'P'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } - /* XXX struni: remove later */ + if (PyLong_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("P"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'P'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } + /* XXX struni: remove later */ /* string */ - if (PyBytes_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } + if (PyBytes_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } /* bytes */ - if (PyByteArray_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } + if (PyByteArray_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } /* unicode */ - if (PyUnicode_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("Z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'Z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } + if (PyUnicode_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("Z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'Z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } /* c_void_p instance (or subclass) */ - if (PyObject_IsInstance(value, type)) { - /* c_void_p instances */ - Py_INCREF(value); - return value; - } + if (PyObject_IsInstance(value, type)) { + /* c_void_p instances */ + Py_INCREF(value); + return value; + } /* ctypes array or pointer instance */ - if (ArrayObject_Check(value) || PointerObject_Check(value)) { - /* Any array or pointer is accepted */ - Py_INCREF(value); - return value; - } + if (ArrayObject_Check(value) || PointerObject_Check(value)) { + /* Any array or pointer is accepted */ + Py_INCREF(value); + return value; + } /* byref(...) */ - if (PyCArg_CheckExact(value)) { - /* byref(c_xxx()) */ - PyCArgObject *a = (PyCArgObject *)value; - if (a->tag == 'P') { - Py_INCREF(value); - return value; - } - } + if (PyCArg_CheckExact(value)) { + /* byref(c_xxx()) */ + PyCArgObject *a = (PyCArgObject *)value; + if (a->tag == 'P') { + Py_INCREF(value); + return value; + } + } /* function pointer */ - if (PyCFuncPtrObject_Check(value)) { - PyCArgObject *parg; - PyCFuncPtrObject *func; - func = (PyCFuncPtrObject *)value; - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'P'; - Py_INCREF(value); - parg->value.p = *(void **)func->b_ptr; - parg->obj = value; - return (PyObject *)parg; - } + if (PyCFuncPtrObject_Check(value)) { + PyCArgObject *parg; + PyCFuncPtrObject *func; + func = (PyCFuncPtrObject *)value; + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'P'; + Py_INCREF(value); + parg->value.p = *(void **)func->b_ptr; + parg->obj = value; + return (PyObject *)parg; + } /* c_char_p, c_wchar_p */ - stgd = PyObject_stgdict(value); - if (stgd && CDataObject_Check(value) && stgd->proto && PyUnicode_Check(stgd->proto)) { - PyCArgObject *parg; - - switch (_PyUnicode_AsString(stgd->proto)[0]) { - case 'z': /* c_char_p */ - case 'Z': /* c_wchar_p */ - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'Z'; - Py_INCREF(value); - parg->obj = value; - /* Remember: b_ptr points to where the pointer is stored! */ - parg->value.p = *(void **)(((CDataObject *)value)->b_ptr); - return (PyObject *)parg; - } - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = c_void_p_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - /* XXX better message */ - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + stgd = PyObject_stgdict(value); + if (stgd && CDataObject_Check(value) && stgd->proto && PyUnicode_Check(stgd->proto)) { + PyCArgObject *parg; + + switch (_PyUnicode_AsString(stgd->proto)[0]) { + case 'z': /* c_char_p */ + case 'Z': /* c_wchar_p */ + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'Z'; + Py_INCREF(value); + parg->obj = value; + /* Remember: b_ptr points to where the pointer is stored! */ + parg->value.p = *(void **)(((CDataObject *)value)->b_ptr); + return (PyObject *)parg; + } + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = c_void_p_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + /* XXX better message */ + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyMethodDef c_void_p_method = { "from_param", c_void_p_from_param, METH_O }; @@ -1718,278 +1718,278 @@ static PyMethodDef c_char_p_method = { "from_param", c_char_p_from_param, METH_O static PyMethodDef c_wchar_p_method = { "from_param", c_wchar_p_from_param, METH_O }; static PyObject *CreateSwappedType(PyTypeObject *type, PyObject *args, PyObject *kwds, - PyObject *proto, struct fielddesc *fmt) + PyObject *proto, struct fielddesc *fmt) { - PyTypeObject *result; - StgDictObject *stgdict; - PyObject *name = PyTuple_GET_ITEM(args, 0); - PyObject *newname; - PyObject *swapped_args; - static PyObject *suffix; - Py_ssize_t i; - - swapped_args = PyTuple_New(PyTuple_GET_SIZE(args)); - if (!swapped_args) - return NULL; - - if (suffix == NULL) + PyTypeObject *result; + StgDictObject *stgdict; + PyObject *name = PyTuple_GET_ITEM(args, 0); + PyObject *newname; + PyObject *swapped_args; + static PyObject *suffix; + Py_ssize_t i; + + swapped_args = PyTuple_New(PyTuple_GET_SIZE(args)); + if (!swapped_args) + return NULL; + + if (suffix == NULL) #ifdef WORDS_BIGENDIAN - suffix = PyUnicode_InternFromString("_le"); + suffix = PyUnicode_InternFromString("_le"); #else - suffix = PyUnicode_InternFromString("_be"); + suffix = PyUnicode_InternFromString("_be"); #endif - newname = PyUnicode_Concat(name, suffix); - if (newname == NULL) { - return NULL; - } - - PyTuple_SET_ITEM(swapped_args, 0, newname); - for (i=1; i<PyTuple_GET_SIZE(args); ++i) { - PyObject *v = PyTuple_GET_ITEM(args, i); - Py_INCREF(v); - PyTuple_SET_ITEM(swapped_args, i, v); - } - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, swapped_args, kwds); - Py_DECREF(swapped_args); - if (result == NULL) - return NULL; - - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) /* XXX leaks result! */ - return NULL; - - stgdict->ffi_type_pointer = *fmt->pffi_type; - stgdict->align = fmt->pffi_type->alignment; - stgdict->length = 0; - stgdict->size = fmt->pffi_type->size; - stgdict->setfunc = fmt->setfunc_swapped; - stgdict->getfunc = fmt->getfunc_swapped; - - Py_INCREF(proto); - stgdict->proto = proto; - - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; - - return (PyObject *)result; + newname = PyUnicode_Concat(name, suffix); + if (newname == NULL) { + return NULL; + } + + PyTuple_SET_ITEM(swapped_args, 0, newname); + for (i=1; i<PyTuple_GET_SIZE(args); ++i) { + PyObject *v = PyTuple_GET_ITEM(args, i); + Py_INCREF(v); + PyTuple_SET_ITEM(swapped_args, i, v); + } + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, swapped_args, kwds); + Py_DECREF(swapped_args); + if (result == NULL) + return NULL; + + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) /* XXX leaks result! */ + return NULL; + + stgdict->ffi_type_pointer = *fmt->pffi_type; + stgdict->align = fmt->pffi_type->alignment; + stgdict->length = 0; + stgdict->size = fmt->pffi_type->size; + stgdict->setfunc = fmt->setfunc_swapped; + stgdict->getfunc = fmt->getfunc_swapped; + + Py_INCREF(proto); + stgdict->proto = proto; + + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + + return (PyObject *)result; } static PyCArgObject * PyCSimpleType_paramfunc(CDataObject *self) { - StgDictObject *dict; - char *fmt; - PyCArgObject *parg; - struct fielddesc *fd; - - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for CDataObject instances */ - fmt = _PyUnicode_AsString(dict->proto); - assert(fmt); - - fd = _ctypes_get_fielddesc(fmt); - assert(fd); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = fmt[0]; - parg->pffi_type = fd->pffi_type; - Py_INCREF(self); - parg->obj = (PyObject *)self; - memcpy(&parg->value, self->b_ptr, self->b_size); - return parg; + StgDictObject *dict; + char *fmt; + PyCArgObject *parg; + struct fielddesc *fd; + + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for CDataObject instances */ + fmt = _PyUnicode_AsString(dict->proto); + assert(fmt); + + fd = _ctypes_get_fielddesc(fmt); + assert(fd); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = fmt[0]; + parg->pffi_type = fd->pffi_type; + Py_INCREF(self); + parg->obj = (PyObject *)self; + memcpy(&parg->value, self->b_ptr, self->b_size); + return parg; } static PyObject * PyCSimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; - PyObject *proto; - const char *proto_str; - Py_ssize_t proto_len; - PyMethodDef *ml; - struct fielddesc *fmt; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) - return NULL; - - proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */ - if (!proto) { - PyErr_SetString(PyExc_AttributeError, - "class must define a '_type_' attribute"); + PyTypeObject *result; + StgDictObject *stgdict; + PyObject *proto; + const char *proto_str; + Py_ssize_t proto_len; + PyMethodDef *ml; + struct fielddesc *fmt; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) + return NULL; + + proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */ + if (!proto) { + PyErr_SetString(PyExc_AttributeError, + "class must define a '_type_' attribute"); error: - Py_XDECREF(proto); - Py_XDECREF(result); - return NULL; - } - if (PyUnicode_Check(proto)) { - PyObject *v = _PyUnicode_AsDefaultEncodedString(proto, NULL); - if (!v) - goto error; - proto_str = PyBytes_AS_STRING(v); - proto_len = PyBytes_GET_SIZE(v); - } else { - PyErr_SetString(PyExc_TypeError, - "class must define a '_type_' string attribute"); - goto error; - } - if (proto_len != 1) { - PyErr_SetString(PyExc_ValueError, - "class must define a '_type_' attribute " - "which must be a string of length 1"); - goto error; - } - if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) { - PyErr_Format(PyExc_AttributeError, - "class must define a '_type_' attribute which must be\n" - "a single character string containing one of '%s'.", - SIMPLE_TYPE_CHARS); - goto error; - } - fmt = _ctypes_get_fielddesc(proto_str); - if (fmt == NULL) { - PyErr_Format(PyExc_ValueError, - "_type_ '%s' not supported", proto_str); - goto error; - } - - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - goto error; - - stgdict->ffi_type_pointer = *fmt->pffi_type; - stgdict->align = fmt->pffi_type->alignment; - stgdict->length = 0; - stgdict->size = fmt->pffi_type->size; - stgdict->setfunc = fmt->setfunc; - stgdict->getfunc = fmt->getfunc; + Py_XDECREF(proto); + Py_XDECREF(result); + return NULL; + } + if (PyUnicode_Check(proto)) { + PyObject *v = _PyUnicode_AsDefaultEncodedString(proto, NULL); + if (!v) + goto error; + proto_str = PyBytes_AS_STRING(v); + proto_len = PyBytes_GET_SIZE(v); + } else { + PyErr_SetString(PyExc_TypeError, + "class must define a '_type_' string attribute"); + goto error; + } + if (proto_len != 1) { + PyErr_SetString(PyExc_ValueError, + "class must define a '_type_' attribute " + "which must be a string of length 1"); + goto error; + } + if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) { + PyErr_Format(PyExc_AttributeError, + "class must define a '_type_' attribute which must be\n" + "a single character string containing one of '%s'.", + SIMPLE_TYPE_CHARS); + goto error; + } + fmt = _ctypes_get_fielddesc(proto_str); + if (fmt == NULL) { + PyErr_Format(PyExc_ValueError, + "_type_ '%s' not supported", proto_str); + goto error; + } + + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + goto error; + + stgdict->ffi_type_pointer = *fmt->pffi_type; + stgdict->align = fmt->pffi_type->alignment; + stgdict->length = 0; + stgdict->size = fmt->pffi_type->size; + stgdict->setfunc = fmt->setfunc; + stgdict->getfunc = fmt->getfunc; #ifdef WORDS_BIGENDIAN - stgdict->format = _ctypes_alloc_format_string(">", proto_str); + stgdict->format = _ctypes_alloc_format_string(">", proto_str); #else - stgdict->format = _ctypes_alloc_format_string("<", proto_str); + stgdict->format = _ctypes_alloc_format_string("<", proto_str); #endif - if (stgdict->format == NULL) { - Py_DECREF(result); - Py_DECREF(proto); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - stgdict->paramfunc = PyCSimpleType_paramfunc; + if (stgdict->format == NULL) { + Py_DECREF(result); + Py_DECREF(proto); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + stgdict->paramfunc = PyCSimpleType_paramfunc; /* - if (result->tp_base != &Simple_Type) { - stgdict->setfunc = NULL; - stgdict->getfunc = NULL; - } + if (result->tp_base != &Simple_Type) { + stgdict->setfunc = NULL; + stgdict->getfunc = NULL; + } */ - /* This consumes the refcount on proto which we have */ - stgdict->proto = proto; - - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; - - /* Install from_param class methods in ctypes base classes. - Overrides the PyCSimpleType_from_param generic method. - */ - if (result->tp_base == &Simple_Type) { - switch (*proto_str) { - case 'z': /* c_char_p */ - ml = &c_char_p_method; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - case 'Z': /* c_wchar_p */ - ml = &c_wchar_p_method; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - case 'P': /* c_void_p */ - ml = &c_void_p_method; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - case 's': - case 'X': - case 'O': - ml = NULL; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - default: - ml = NULL; - break; - } - - if (ml) { - PyObject *meth; - int x; - meth = PyDescr_NewClassMethod(result, ml); - if (!meth) - return NULL; - x = PyDict_SetItemString(result->tp_dict, - ml->ml_name, - meth); - Py_DECREF(meth); - if (x == -1) { - Py_DECREF(result); - return NULL; - } - } - } - - if (type == &PyCSimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) { - PyObject *swapped = CreateSwappedType(type, args, kwds, - proto, fmt); - StgDictObject *sw_dict; - if (swapped == NULL) { - Py_DECREF(result); - return NULL; - } - sw_dict = PyType_stgdict(swapped); + /* This consumes the refcount on proto which we have */ + stgdict->proto = proto; + + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + + /* Install from_param class methods in ctypes base classes. + Overrides the PyCSimpleType_from_param generic method. + */ + if (result->tp_base == &Simple_Type) { + switch (*proto_str) { + case 'z': /* c_char_p */ + ml = &c_char_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + case 'Z': /* c_wchar_p */ + ml = &c_wchar_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + case 'P': /* c_void_p */ + ml = &c_void_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + case 's': + case 'X': + case 'O': + ml = NULL; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + default: + ml = NULL; + break; + } + + if (ml) { + PyObject *meth; + int x; + meth = PyDescr_NewClassMethod(result, ml); + if (!meth) + return NULL; + x = PyDict_SetItemString(result->tp_dict, + ml->ml_name, + meth); + Py_DECREF(meth); + if (x == -1) { + Py_DECREF(result); + return NULL; + } + } + } + + if (type == &PyCSimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) { + PyObject *swapped = CreateSwappedType(type, args, kwds, + proto, fmt); + StgDictObject *sw_dict; + if (swapped == NULL) { + Py_DECREF(result); + return NULL; + } + sw_dict = PyType_stgdict(swapped); #ifdef WORDS_BIGENDIAN - PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped); - PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_le__", swapped); - /* We are creating the type for the OTHER endian */ - sw_dict->format = _ctypes_alloc_format_string("<", stgdict->format+1); + PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped); + PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_le__", swapped); + /* We are creating the type for the OTHER endian */ + sw_dict->format = _ctypes_alloc_format_string("<", stgdict->format+1); #else - PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped); - PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_be__", swapped); - /* We are creating the type for the OTHER endian */ - sw_dict->format = _ctypes_alloc_format_string(">", stgdict->format+1); + PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped); + PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_be__", swapped); + /* We are creating the type for the OTHER endian */ + sw_dict->format = _ctypes_alloc_format_string(">", stgdict->format+1); #endif - Py_DECREF(swapped); - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } - }; - - return (PyObject *)result; + Py_DECREF(swapped); + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } + }; + + return (PyObject *)result; } /* @@ -1999,101 +1999,101 @@ PyCSimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) static PyObject * PyCSimpleType_from_param(PyObject *type, PyObject *value) { - StgDictObject *dict; - char *fmt; - PyCArgObject *parg; - struct fielddesc *fd; - PyObject *as_parameter; - - /* If the value is already an instance of the requested type, - we can use it as is */ - if (1 == PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - - dict = PyType_stgdict(type); - assert(dict); - - /* I think we can rely on this being a one-character string */ - fmt = _PyUnicode_AsString(dict->proto); - assert(fmt); - - fd = _ctypes_get_fielddesc(fmt); - assert(fd); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = fmt[0]; - parg->pffi_type = fd->pffi_type; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj) - return (PyObject *)parg; - PyErr_Clear(); - Py_DECREF(parg); - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = PyCSimpleType_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + StgDictObject *dict; + char *fmt; + PyCArgObject *parg; + struct fielddesc *fd; + PyObject *as_parameter; + + /* If the value is already an instance of the requested type, + we can use it as is */ + if (1 == PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + + dict = PyType_stgdict(type); + assert(dict); + + /* I think we can rely on this being a one-character string */ + fmt = _PyUnicode_AsString(dict->proto); + assert(fmt); + + fd = _ctypes_get_fielddesc(fmt); + assert(fd); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = fmt[0]; + parg->pffi_type = fd->pffi_type; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj) + return (PyObject *)parg; + PyErr_Clear(); + Py_DECREF(parg); + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = PyCSimpleType_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyMethodDef PyCSimpleType_methods[] = { - { "from_param", PyCSimpleType_from_param, METH_O, from_param_doc }, - { "from_address", CDataType_from_address, METH_O, from_address_doc }, - { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, - { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, - { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, - { NULL, NULL }, + { "from_param", PyCSimpleType_from_param, METH_O, from_param_doc }, + { "from_address", CDataType_from_address, METH_O, from_address_doc }, + { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, + { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, + { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, + { NULL, NULL }, }; PyTypeObject PyCSimpleType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCSimpleType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "metatype for the PyCSimpleType Objects", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PyCSimpleType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCSimpleType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCSimpleType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "metatype for the PyCSimpleType Objects", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PyCSimpleType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCSimpleType_new, /* tp_new */ + 0, /* tp_free */ }; /******************************************************************/ @@ -2104,217 +2104,217 @@ PyTypeObject PyCSimpleType_Type = { static PyObject * converters_from_argtypes(PyObject *ob) { - PyObject *converters; - Py_ssize_t i; - Py_ssize_t nArgs; - - ob = PySequence_Tuple(ob); /* new reference */ - if (!ob) { - PyErr_SetString(PyExc_TypeError, - "_argtypes_ must be a sequence of types"); - return NULL; - } - - nArgs = PyTuple_GET_SIZE(ob); - converters = PyTuple_New(nArgs); - if (!converters) - return NULL; - - /* I have to check if this is correct. Using c_char, which has a size - of 1, will be assumed to be pushed as only one byte! - Aren't these promoted to integers by the C compiler and pushed as 4 bytes? - */ - - for (i = 0; i < nArgs; ++i) { - PyObject *tp = PyTuple_GET_ITEM(ob, i); - PyObject *cnv = PyObject_GetAttrString(tp, "from_param"); - if (!cnv) - goto argtypes_error_1; - PyTuple_SET_ITEM(converters, i, cnv); - } - Py_DECREF(ob); - return converters; + PyObject *converters; + Py_ssize_t i; + Py_ssize_t nArgs; + + ob = PySequence_Tuple(ob); /* new reference */ + if (!ob) { + PyErr_SetString(PyExc_TypeError, + "_argtypes_ must be a sequence of types"); + return NULL; + } + + nArgs = PyTuple_GET_SIZE(ob); + converters = PyTuple_New(nArgs); + if (!converters) + return NULL; + + /* I have to check if this is correct. Using c_char, which has a size + of 1, will be assumed to be pushed as only one byte! + Aren't these promoted to integers by the C compiler and pushed as 4 bytes? + */ + + for (i = 0; i < nArgs; ++i) { + PyObject *tp = PyTuple_GET_ITEM(ob, i); + PyObject *cnv = PyObject_GetAttrString(tp, "from_param"); + if (!cnv) + goto argtypes_error_1; + PyTuple_SET_ITEM(converters, i, cnv); + } + Py_DECREF(ob); + return converters; argtypes_error_1: - Py_XDECREF(converters); - Py_DECREF(ob); - PyErr_Format(PyExc_TypeError, - "item %zd in _argtypes_ has no from_param method", - i+1); - return NULL; + Py_XDECREF(converters); + Py_DECREF(ob); + PyErr_Format(PyExc_TypeError, + "item %zd in _argtypes_ has no from_param method", + i+1); + return NULL; } static int make_funcptrtype_dict(StgDictObject *stgdict) { - PyObject *ob; - PyObject *converters = NULL; - - stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; - stgdict->length = 1; - stgdict->size = sizeof(void *); - stgdict->setfunc = NULL; - stgdict->getfunc = NULL; - stgdict->ffi_type_pointer = ffi_type_pointer; - - ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_"); - if (!ob || !PyLong_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "class must define _flags_ which must be an integer"); - return -1; - } - stgdict->flags = PyLong_AS_LONG(ob) | TYPEFLAG_ISPOINTER; - - /* _argtypes_ is optional... */ - ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_"); - if (ob) { - converters = converters_from_argtypes(ob); - if (!converters) - goto error; - Py_INCREF(ob); - stgdict->argtypes = ob; - stgdict->converters = converters; - } - - ob = PyDict_GetItemString((PyObject *)stgdict, "_restype_"); - if (ob) { - if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "_restype_ must be a type, a callable, or None"); - return -1; - } - Py_INCREF(ob); - stgdict->restype = ob; - stgdict->checker = PyObject_GetAttrString(ob, "_check_retval_"); - if (stgdict->checker == NULL) - PyErr_Clear(); - } + PyObject *ob; + PyObject *converters = NULL; + + stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; + stgdict->length = 1; + stgdict->size = sizeof(void *); + stgdict->setfunc = NULL; + stgdict->getfunc = NULL; + stgdict->ffi_type_pointer = ffi_type_pointer; + + ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_"); + if (!ob || !PyLong_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "class must define _flags_ which must be an integer"); + return -1; + } + stgdict->flags = PyLong_AS_LONG(ob) | TYPEFLAG_ISPOINTER; + + /* _argtypes_ is optional... */ + ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_"); + if (ob) { + converters = converters_from_argtypes(ob); + if (!converters) + goto error; + Py_INCREF(ob); + stgdict->argtypes = ob; + stgdict->converters = converters; + } + + ob = PyDict_GetItemString((PyObject *)stgdict, "_restype_"); + if (ob) { + if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "_restype_ must be a type, a callable, or None"); + return -1; + } + Py_INCREF(ob); + stgdict->restype = ob; + stgdict->checker = PyObject_GetAttrString(ob, "_check_retval_"); + if (stgdict->checker == NULL) + PyErr_Clear(); + } /* XXX later, maybe. - ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_"); - if (ob) { - if (!PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "_errcheck_ must be callable"); - return -1; - } - Py_INCREF(ob); - stgdict->errcheck = ob; - } + ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_"); + if (ob) { + if (!PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "_errcheck_ must be callable"); + return -1; + } + Py_INCREF(ob); + stgdict->errcheck = ob; + } */ - return 0; + return 0; error: - Py_XDECREF(converters); - return -1; + Py_XDECREF(converters); + return -1; } static PyCArgObject * PyCFuncPtrType_paramfunc(CDataObject *self) { - PyCArgObject *parg; - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - Py_INCREF(self); - parg->obj = (PyObject *)self; - parg->value.p = *(void **)self->b_ptr; - return parg; + PyCArgObject *parg; + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + Py_INCREF(self); + parg->obj = (PyObject *)self; + parg->value.p = *(void **)self->b_ptr; + return parg; } static PyObject * PyCFuncPtrType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; - - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - return NULL; - - stgdict->paramfunc = PyCFuncPtrType_paramfunc; - /* We do NOT expose the function signature in the format string. It - is impossible, generally, because the only requirement for the - argtypes items is that they have a .from_param method - we do not - know the types of the arguments (although, in practice, most - argtypes would be a ctypes type). - */ - stgdict->format = _ctypes_alloc_format_string(NULL, "X{}"); - stgdict->flags |= TYPEFLAG_ISPOINTER; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - /* replace the class dict by our updated storage dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; - - if (-1 == make_funcptrtype_dict(stgdict)) { - Py_DECREF(result); - return NULL; - } - - return (PyObject *)result; + PyTypeObject *result; + StgDictObject *stgdict; + + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + return NULL; + + stgdict->paramfunc = PyCFuncPtrType_paramfunc; + /* We do NOT expose the function signature in the format string. It + is impossible, generally, because the only requirement for the + argtypes items is that they have a .from_param method - we do not + know the types of the arguments (although, in practice, most + argtypes would be a ctypes type). + */ + stgdict->format = _ctypes_alloc_format_string(NULL, "X{}"); + stgdict->flags |= TYPEFLAG_ISPOINTER; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + /* replace the class dict by our updated storage dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + + if (-1 == make_funcptrtype_dict(stgdict)) { + Py_DECREF(result); + return NULL; + } + + return (PyObject *)result; } PyTypeObject PyCFuncPtrType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCFuncPtrType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for C function pointers", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCFuncPtrType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCFuncPtrType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for C function pointers", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCFuncPtrType_new, /* tp_new */ + 0, /* tp_free */ }; - + /***************************************************************** * Code to keep needed objects alive */ @@ -2322,46 +2322,46 @@ PyTypeObject PyCFuncPtrType_Type = { static CDataObject * PyCData_GetContainer(CDataObject *self) { - while (self->b_base) - self = self->b_base; - if (self->b_objects == NULL) { - if (self->b_length) { - self->b_objects = PyDict_New(); - } else { - Py_INCREF(Py_None); - self->b_objects = Py_None; - } - } - return self; + while (self->b_base) + self = self->b_base; + if (self->b_objects == NULL) { + if (self->b_length) { + self->b_objects = PyDict_New(); + } else { + Py_INCREF(Py_None); + self->b_objects = Py_None; + } + } + return self; } static PyObject * GetKeepedObjects(CDataObject *target) { - return PyCData_GetContainer(target)->b_objects; + return PyCData_GetContainer(target)->b_objects; } static PyObject * unique_key(CDataObject *target, Py_ssize_t index) { - char string[256]; - char *cp = string; - size_t bytes_left; - - assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2); - cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); - while (target->b_base) { - bytes_left = sizeof(string) - (cp - string) - 1; - /* Hex format needs 2 characters per byte */ - if (bytes_left < sizeof(Py_ssize_t) * 2) { - PyErr_SetString(PyExc_ValueError, - "ctypes object structure too deep"); - return NULL; - } - cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int)); - target = target->b_base; - } - return PyUnicode_FromStringAndSize(string, cp-string); + char string[256]; + char *cp = string; + size_t bytes_left; + + assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2); + cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); + while (target->b_base) { + bytes_left = sizeof(string) - (cp - string) - 1; + /* Hex format needs 2 characters per byte */ + if (bytes_left < sizeof(Py_ssize_t) * 2) { + PyErr_SetString(PyExc_ValueError, + "ctypes object structure too deep"); + return NULL; + } + cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int)); + target = target->b_base; + } + return PyUnicode_FromStringAndSize(string, cp-string); } /* @@ -2385,30 +2385,30 @@ unique_key(CDataObject *target, Py_ssize_t index) static int KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep) { - int result; - CDataObject *ob; - PyObject *key; + int result; + CDataObject *ob; + PyObject *key; /* Optimization: no need to store None */ - if (keep == Py_None) { - Py_DECREF(Py_None); - return 0; - } - ob = PyCData_GetContainer(target); - if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) { - Py_XDECREF(ob->b_objects); - ob->b_objects = keep; /* refcount consumed */ - return 0; - } - key = unique_key(target, index); - if (key == NULL) { - Py_DECREF(keep); - return -1; - } - result = PyDict_SetItem(ob->b_objects, key, keep); - Py_DECREF(key); - Py_DECREF(keep); - return result; + if (keep == Py_None) { + Py_DECREF(Py_None); + return 0; + } + ob = PyCData_GetContainer(target); + if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) { + Py_XDECREF(ob->b_objects); + ob->b_objects = keep; /* refcount consumed */ + return 0; + } + key = unique_key(target, index); + if (key == NULL) { + Py_DECREF(keep); + return -1; + } + result = PyDict_SetItem(ob->b_objects, key, keep); + Py_DECREF(key); + Py_DECREF(keep); + return result; } /******************************************************************/ @@ -2418,75 +2418,75 @@ KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep) static int PyCData_traverse(CDataObject *self, visitproc visit, void *arg) { - Py_VISIT(self->b_objects); - Py_VISIT((PyObject *)self->b_base); - return 0; + Py_VISIT(self->b_objects); + Py_VISIT((PyObject *)self->b_base); + return 0; } static int PyCData_clear(CDataObject *self) { - StgDictObject *dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for CDataObject instances */ - Py_CLEAR(self->b_objects); - if ((self->b_needsfree) - && ((size_t)dict->size > sizeof(self->b_value))) - PyMem_Free(self->b_ptr); - self->b_ptr = NULL; - Py_CLEAR(self->b_base); - return 0; + StgDictObject *dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for CDataObject instances */ + Py_CLEAR(self->b_objects); + if ((self->b_needsfree) + && ((size_t)dict->size > sizeof(self->b_value))) + PyMem_Free(self->b_ptr); + self->b_ptr = NULL; + Py_CLEAR(self->b_base); + return 0; } static void PyCData_dealloc(PyObject *self) { - PyCData_clear((CDataObject *)self); - Py_TYPE(self)->tp_free(self); + PyCData_clear((CDataObject *)self); + Py_TYPE(self)->tp_free(self); } static PyMemberDef PyCData_members[] = { - { "_b_base_", T_OBJECT, - offsetof(CDataObject, b_base), READONLY, - "the base object" }, - { "_b_needsfree_", T_INT, - offsetof(CDataObject, b_needsfree), READONLY, - "whether the object owns the memory or not" }, - { "_objects", T_OBJECT, - offsetof(CDataObject, b_objects), READONLY, - "internal objects tree (NEVER CHANGE THIS OBJECT!)"}, - { NULL }, + { "_b_base_", T_OBJECT, + offsetof(CDataObject, b_base), READONLY, + "the base object" }, + { "_b_needsfree_", T_INT, + offsetof(CDataObject, b_needsfree), READONLY, + "whether the object owns the memory or not" }, + { "_objects", T_OBJECT, + offsetof(CDataObject, b_objects), READONLY, + "internal objects tree (NEVER CHANGE THIS OBJECT!)"}, + { NULL }, }; static int PyCData_NewGetBuffer(PyObject *_self, Py_buffer *view, int flags) { - CDataObject *self = (CDataObject *)_self; - StgDictObject *dict = PyObject_stgdict(_self); - Py_ssize_t i; - - if (view == NULL) return 0; - - view->buf = self->b_ptr; - view->obj = _self; - Py_INCREF(_self); - view->len = self->b_size; - view->readonly = 0; - /* use default format character if not set */ - view->format = dict->format ? dict->format : "B"; - view->ndim = dict->ndim; - view->shape = dict->shape; - view->itemsize = self->b_size; - for (i = 0; i < view->ndim; ++i) { - view->itemsize /= dict->shape[i]; - } - view->strides = NULL; - view->suboffsets = NULL; - view->internal = NULL; - return 0; + CDataObject *self = (CDataObject *)_self; + StgDictObject *dict = PyObject_stgdict(_self); + Py_ssize_t i; + + if (view == NULL) return 0; + + view->buf = self->b_ptr; + view->obj = _self; + Py_INCREF(_self); + view->len = self->b_size; + view->readonly = 0; + /* use default format character if not set */ + view->format = dict->format ? dict->format : "B"; + view->ndim = dict->ndim; + view->shape = dict->shape; + view->itemsize = self->b_size; + for (i = 0; i < view->ndim; ++i) { + view->itemsize /= dict->shape[i]; + } + view->strides = NULL; + view->suboffsets = NULL; + view->internal = NULL; + return 0; } static PyBufferProcs PyCData_as_buffer = { - PyCData_NewGetBuffer, - NULL, + PyCData_NewGetBuffer, + NULL, }; /* @@ -2495,47 +2495,47 @@ static PyBufferProcs PyCData_as_buffer = { static long PyCData_nohash(PyObject *self) { - PyErr_SetString(PyExc_TypeError, "unhashable type"); - return -1; + PyErr_SetString(PyExc_TypeError, "unhashable type"); + return -1; } static PyObject * PyCData_reduce(PyObject *_self, PyObject *args) { - CDataObject *self = (CDataObject *)_self; - - if (PyObject_stgdict(_self)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) { - PyErr_SetString(PyExc_ValueError, - "ctypes objects containing pointers cannot be pickled"); - return NULL; - } - return Py_BuildValue("O(O(NN))", - _unpickle, - Py_TYPE(_self), - PyObject_GetAttrString(_self, "__dict__"), - PyBytes_FromStringAndSize(self->b_ptr, self->b_size)); + CDataObject *self = (CDataObject *)_self; + + if (PyObject_stgdict(_self)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) { + PyErr_SetString(PyExc_ValueError, + "ctypes objects containing pointers cannot be pickled"); + return NULL; + } + return Py_BuildValue("O(O(NN))", + _unpickle, + Py_TYPE(_self), + PyObject_GetAttrString(_self, "__dict__"), + PyBytes_FromStringAndSize(self->b_ptr, self->b_size)); } static PyObject * PyCData_setstate(PyObject *_self, PyObject *args) { - void *data; - Py_ssize_t len; - int res; - PyObject *dict, *mydict; - CDataObject *self = (CDataObject *)_self; - if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len)) - return NULL; - if (len > self->b_size) - len = self->b_size; - memmove(self->b_ptr, data, len); - mydict = PyObject_GetAttrString(_self, "__dict__"); - res = PyDict_Update(mydict, dict); - Py_DECREF(mydict); - if (res == -1) - return NULL; - Py_INCREF(Py_None); - return Py_None; + void *data; + Py_ssize_t len; + int res; + PyObject *dict, *mydict; + CDataObject *self = (CDataObject *)_self; + if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len)) + return NULL; + if (len > self->b_size) + len = self->b_size; + memmove(self->b_ptr, data, len); + mydict = PyObject_GetAttrString(_self, "__dict__"); + res = PyDict_Update(mydict, dict); + Py_DECREF(mydict); + if (res == -1) + return NULL; + Py_INCREF(Py_None); + return Py_None; } /* @@ -2544,124 +2544,124 @@ PyCData_setstate(PyObject *_self, PyObject *args) static PyObject * PyCData_from_outparam(PyObject *self, PyObject *args) { - Py_INCREF(self); - return self; + Py_INCREF(self); + return self; } static PyMethodDef PyCData_methods[] = { - { "__ctypes_from_outparam__", PyCData_from_outparam, METH_NOARGS, }, - { "__reduce__", PyCData_reduce, METH_NOARGS, }, - { "__setstate__", PyCData_setstate, METH_VARARGS, }, - { NULL, NULL }, + { "__ctypes_from_outparam__", PyCData_from_outparam, METH_NOARGS, }, + { "__reduce__", PyCData_reduce, METH_NOARGS, }, + { "__setstate__", PyCData_setstate, METH_VARARGS, }, + { NULL, NULL }, }; PyTypeObject PyCData_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes._CData", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - PyCData_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - PyCData_nohash, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PyCData_methods, /* tp_methods */ - PyCData_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes._CData", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + PyCData_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + PyCData_nohash, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PyCData_methods, /* tp_methods */ + PyCData_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; static int PyCData_MallocBuffer(CDataObject *obj, StgDictObject *dict) { - if ((size_t)dict->size <= sizeof(obj->b_value)) { - /* No need to call malloc, can use the default buffer */ - obj->b_ptr = (char *)&obj->b_value; - /* The b_needsfree flag does not mean that we actually did - call PyMem_Malloc to allocate the memory block; instead it - means we are the *owner* of the memory and are responsible - for freeing resources associated with the memory. This is - also the reason that b_needsfree is exposed to Python. - */ - obj->b_needsfree = 1; - } else { - /* In python 2.4, and ctypes 0.9.6, the malloc call took about - 33% of the creation time for c_int(). - */ - obj->b_ptr = (char *)PyMem_Malloc(dict->size); - if (obj->b_ptr == NULL) { - PyErr_NoMemory(); - return -1; - } - obj->b_needsfree = 1; - memset(obj->b_ptr, 0, dict->size); - } - obj->b_size = dict->size; - return 0; + if ((size_t)dict->size <= sizeof(obj->b_value)) { + /* No need to call malloc, can use the default buffer */ + obj->b_ptr = (char *)&obj->b_value; + /* The b_needsfree flag does not mean that we actually did + call PyMem_Malloc to allocate the memory block; instead it + means we are the *owner* of the memory and are responsible + for freeing resources associated with the memory. This is + also the reason that b_needsfree is exposed to Python. + */ + obj->b_needsfree = 1; + } else { + /* In python 2.4, and ctypes 0.9.6, the malloc call took about + 33% of the creation time for c_int(). + */ + obj->b_ptr = (char *)PyMem_Malloc(dict->size); + if (obj->b_ptr == NULL) { + PyErr_NoMemory(); + return -1; + } + obj->b_needsfree = 1; + memset(obj->b_ptr, 0, dict->size); + } + obj->b_size = dict->size; + return 0; } PyObject * PyCData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr) { - CDataObject *cmem; - StgDictObject *dict; - - assert(PyType_Check(type)); - dict = PyType_stgdict(type); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "abstract class"); - return NULL; - } - dict->flags |= DICTFLAG_FINAL; - cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); - if (cmem == NULL) - return NULL; - assert(CDataObject_Check(cmem)); - - cmem->b_length = dict->length; - cmem->b_size = dict->size; - if (base) { /* use base's buffer */ - assert(CDataObject_Check(base)); - cmem->b_ptr = adr; - cmem->b_needsfree = 0; - Py_INCREF(base); - cmem->b_base = (CDataObject *)base; - cmem->b_index = index; - } else { /* copy contents of adr */ - if (-1 == PyCData_MallocBuffer(cmem, dict)) { - return NULL; - Py_DECREF(cmem); - } - memcpy(cmem->b_ptr, adr, dict->size); - cmem->b_index = index; - } - return (PyObject *)cmem; + CDataObject *cmem; + StgDictObject *dict; + + assert(PyType_Check(type)); + dict = PyType_stgdict(type); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "abstract class"); + return NULL; + } + dict->flags |= DICTFLAG_FINAL; + cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); + if (cmem == NULL) + return NULL; + assert(CDataObject_Check(cmem)); + + cmem->b_length = dict->length; + cmem->b_size = dict->size; + if (base) { /* use base's buffer */ + assert(CDataObject_Check(base)); + cmem->b_ptr = adr; + cmem->b_needsfree = 0; + Py_INCREF(base); + cmem->b_base = (CDataObject *)base; + cmem->b_index = index; + } else { /* copy contents of adr */ + if (-1 == PyCData_MallocBuffer(cmem, dict)) { + return NULL; + Py_DECREF(cmem); + } + memcpy(cmem->b_ptr, adr, dict->size); + cmem->b_index = index; + } + return (PyObject *)cmem; } /* @@ -2670,26 +2670,26 @@ PyCData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr) PyObject * PyCData_AtAddress(PyObject *type, void *buf) { - CDataObject *pd; - StgDictObject *dict; - - assert(PyType_Check(type)); - dict = PyType_stgdict(type); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "abstract class"); - return NULL; - } - dict->flags |= DICTFLAG_FINAL; - - pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); - if (!pd) - return NULL; - assert(CDataObject_Check(pd)); - pd->b_ptr = (char *)buf; - pd->b_length = dict->length; - pd->b_size = dict->size; - return (PyObject *)pd; + CDataObject *pd; + StgDictObject *dict; + + assert(PyType_Check(type)); + dict = PyType_stgdict(type); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "abstract class"); + return NULL; + } + dict->flags |= DICTFLAG_FINAL; + + pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); + if (!pd) + return NULL; + assert(CDataObject_Check(pd)); + pd->b_ptr = (char *)buf; + pd->b_length = dict->length; + pd->b_size = dict->size; + return (PyObject *)pd; } /* @@ -2699,25 +2699,25 @@ PyCData_AtAddress(PyObject *type, void *buf) */ int _ctypes_simple_instance(PyObject *obj) { - PyTypeObject *type = (PyTypeObject *)obj; + PyTypeObject *type = (PyTypeObject *)obj; - if (PyCSimpleTypeObject_Check(type)) - return type->tp_base != &Simple_Type; - return 0; + if (PyCSimpleTypeObject_Check(type)) + return type->tp_base != &Simple_Type; + return 0; } PyObject * PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src, - Py_ssize_t index, Py_ssize_t size, char *adr) + Py_ssize_t index, Py_ssize_t size, char *adr) { - StgDictObject *dict; - if (getfunc) - return getfunc(adr, size); - assert(type); - dict = PyType_stgdict(type); - if (dict && dict->getfunc && !_ctypes_simple_instance(type)) - return dict->getfunc(adr, size); - return PyCData_FromBaseObj(type, src, index, adr); + StgDictObject *dict; + if (getfunc) + return getfunc(adr, size); + assert(type); + dict = PyType_stgdict(type); + if (dict && dict->getfunc && !_ctypes_simple_instance(type)) + return dict->getfunc(adr, size); + return PyCData_FromBaseObj(type, src, index, adr); } /* @@ -2725,96 +2725,96 @@ PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src, */ static PyObject * _PyCData_set(CDataObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value, - Py_ssize_t size, char *ptr) + Py_ssize_t size, char *ptr) { - CDataObject *src; - - if (setfunc) - return setfunc(ptr, value, size); - - if (!CDataObject_Check(value)) { - StgDictObject *dict = PyType_stgdict(type); - if (dict && dict->setfunc) - return dict->setfunc(ptr, value, size); - /* - If value is a tuple, we try to call the type with the tuple - and use the result! - */ - assert(PyType_Check(type)); - if (PyTuple_Check(value)) { - PyObject *ob; - PyObject *result; - ob = PyObject_CallObject(type, value); - if (ob == NULL) { - _ctypes_extend_error(PyExc_RuntimeError, "(%s) ", - ((PyTypeObject *)type)->tp_name); - return NULL; - } - result = _PyCData_set(dst, type, setfunc, ob, - size, ptr); - Py_DECREF(ob); - return result; - } else if (value == Py_None && PyCPointerTypeObject_Check(type)) { - *(void **)ptr = NULL; - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_Format(PyExc_TypeError, - "expected %s instance, got %s", - ((PyTypeObject *)type)->tp_name, - Py_TYPE(value)->tp_name); - return NULL; - } - } - src = (CDataObject *)value; - - if (PyObject_IsInstance(value, type)) { - memcpy(ptr, - src->b_ptr, - size); - - if (PyCPointerTypeObject_Check(type)) - /* XXX */; - - value = GetKeepedObjects(src); - Py_INCREF(value); - return value; - } - - if (PyCPointerTypeObject_Check(type) - && ArrayObject_Check(value)) { - StgDictObject *p1, *p2; - PyObject *keep; - p1 = PyObject_stgdict(value); - assert(p1); /* Cannot be NULL for array instances */ - p2 = PyType_stgdict(type); - assert(p2); /* Cannot be NULL for pointer types */ - - if (p1->proto != p2->proto) { - PyErr_Format(PyExc_TypeError, - "incompatible types, %s instance instead of %s instance", - Py_TYPE(value)->tp_name, - ((PyTypeObject *)type)->tp_name); - return NULL; - } - *(void **)ptr = src->b_ptr; - - keep = GetKeepedObjects(src); - /* - We are assigning an array object to a field which represents - a pointer. This has the same effect as converting an array - into a pointer. So, again, we have to keep the whole object - pointed to (which is the array in this case) alive, and not - only it's object list. So we create a tuple, containing - b_objects list PLUS the array itself, and return that! - */ - return PyTuple_Pack(2, keep, value); - } - PyErr_Format(PyExc_TypeError, - "incompatible types, %s instance instead of %s instance", - Py_TYPE(value)->tp_name, - ((PyTypeObject *)type)->tp_name); - return NULL; + CDataObject *src; + + if (setfunc) + return setfunc(ptr, value, size); + + if (!CDataObject_Check(value)) { + StgDictObject *dict = PyType_stgdict(type); + if (dict && dict->setfunc) + return dict->setfunc(ptr, value, size); + /* + If value is a tuple, we try to call the type with the tuple + and use the result! + */ + assert(PyType_Check(type)); + if (PyTuple_Check(value)) { + PyObject *ob; + PyObject *result; + ob = PyObject_CallObject(type, value); + if (ob == NULL) { + _ctypes_extend_error(PyExc_RuntimeError, "(%s) ", + ((PyTypeObject *)type)->tp_name); + return NULL; + } + result = _PyCData_set(dst, type, setfunc, ob, + size, ptr); + Py_DECREF(ob); + return result; + } else if (value == Py_None && PyCPointerTypeObject_Check(type)) { + *(void **)ptr = NULL; + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_Format(PyExc_TypeError, + "expected %s instance, got %s", + ((PyTypeObject *)type)->tp_name, + Py_TYPE(value)->tp_name); + return NULL; + } + } + src = (CDataObject *)value; + + if (PyObject_IsInstance(value, type)) { + memcpy(ptr, + src->b_ptr, + size); + + if (PyCPointerTypeObject_Check(type)) + /* XXX */; + + value = GetKeepedObjects(src); + Py_INCREF(value); + return value; + } + + if (PyCPointerTypeObject_Check(type) + && ArrayObject_Check(value)) { + StgDictObject *p1, *p2; + PyObject *keep; + p1 = PyObject_stgdict(value); + assert(p1); /* Cannot be NULL for array instances */ + p2 = PyType_stgdict(type); + assert(p2); /* Cannot be NULL for pointer types */ + + if (p1->proto != p2->proto) { + PyErr_Format(PyExc_TypeError, + "incompatible types, %s instance instead of %s instance", + Py_TYPE(value)->tp_name, + ((PyTypeObject *)type)->tp_name); + return NULL; + } + *(void **)ptr = src->b_ptr; + + keep = GetKeepedObjects(src); + /* + We are assigning an array object to a field which represents + a pointer. This has the same effect as converting an array + into a pointer. So, again, we have to keep the whole object + pointed to (which is the array in this case) alive, and not + only it's object list. So we create a tuple, containing + b_objects list PLUS the array itself, and return that! + */ + return PyTuple_Pack(2, keep, value); + } + PyErr_Format(PyExc_TypeError, + "incompatible types, %s instance instead of %s instance", + Py_TYPE(value)->tp_name, + ((PyTypeObject *)type)->tp_name); + return NULL; } /* @@ -2823,58 +2823,58 @@ _PyCData_set(CDataObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value, */ int PyCData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value, - Py_ssize_t index, Py_ssize_t size, char *ptr) + Py_ssize_t index, Py_ssize_t size, char *ptr) { - CDataObject *mem = (CDataObject *)dst; - PyObject *result; - - if (!CDataObject_Check(dst)) { - PyErr_SetString(PyExc_TypeError, - "not a ctype instance"); - return -1; - } - - result = _PyCData_set(mem, type, setfunc, value, - size, ptr); - if (result == NULL) - return -1; - - /* KeepRef steals a refcount from it's last argument */ - /* If KeepRef fails, we are stumped. The dst memory block has already - been changed */ - return KeepRef(mem, index, result); + CDataObject *mem = (CDataObject *)dst; + PyObject *result; + + if (!CDataObject_Check(dst)) { + PyErr_SetString(PyExc_TypeError, + "not a ctype instance"); + return -1; + } + + result = _PyCData_set(mem, type, setfunc, value, + size, ptr); + if (result == NULL) + return -1; + + /* KeepRef steals a refcount from it's last argument */ + /* If KeepRef fails, we are stumped. The dst memory block has already + been changed */ + return KeepRef(mem, index, result); } - + /******************************************************************/ static PyObject * GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - CDataObject *obj; - StgDictObject *dict; - - dict = PyType_stgdict((PyObject *)type); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "abstract class"); - return NULL; - } - dict->flags |= DICTFLAG_FINAL; - - obj = (CDataObject *)type->tp_alloc(type, 0); - if (!obj) - return NULL; - - obj->b_base = NULL; - obj->b_index = 0; - obj->b_objects = NULL; - obj->b_length = dict->length; - - if (-1 == PyCData_MallocBuffer(obj, dict)) { - Py_DECREF(obj); - return NULL; - } - return (PyObject *)obj; + CDataObject *obj; + StgDictObject *dict; + + dict = PyType_stgdict((PyObject *)type); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "abstract class"); + return NULL; + } + dict->flags |= DICTFLAG_FINAL; + + obj = (CDataObject *)type->tp_alloc(type, 0); + if (!obj) + return NULL; + + obj->b_base = NULL; + obj->b_index = 0; + obj->b_objects = NULL; + obj->b_length = dict->length; + + if (-1 == PyCData_MallocBuffer(obj, dict)) { + Py_DECREF(obj); + return NULL; + } + return (PyObject *)obj; } /*****************************************************************/ /* @@ -2884,165 +2884,165 @@ GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds) static int PyCFuncPtr_set_errcheck(PyCFuncPtrObject *self, PyObject *ob) { - if (ob && !PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "the errcheck attribute must be callable"); - return -1; - } - Py_XDECREF(self->errcheck); - Py_XINCREF(ob); - self->errcheck = ob; - return 0; + if (ob && !PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "the errcheck attribute must be callable"); + return -1; + } + Py_XDECREF(self->errcheck); + Py_XINCREF(ob); + self->errcheck = ob; + return 0; } static PyObject * PyCFuncPtr_get_errcheck(PyCFuncPtrObject *self) { - if (self->errcheck) { - Py_INCREF(self->errcheck); - return self->errcheck; - } - Py_INCREF(Py_None); - return Py_None; + if (self->errcheck) { + Py_INCREF(self->errcheck); + return self->errcheck; + } + Py_INCREF(Py_None); + return Py_None; } static int PyCFuncPtr_set_restype(PyCFuncPtrObject *self, PyObject *ob) { - if (ob == NULL) { - Py_XDECREF(self->restype); - self->restype = NULL; - Py_XDECREF(self->checker); - self->checker = NULL; - return 0; - } - if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "restype must be a type, a callable, or None"); - return -1; - } - Py_XDECREF(self->checker); - Py_XDECREF(self->restype); - Py_INCREF(ob); - self->restype = ob; - self->checker = PyObject_GetAttrString(ob, "_check_retval_"); - if (self->checker == NULL) - PyErr_Clear(); - return 0; + if (ob == NULL) { + Py_XDECREF(self->restype); + self->restype = NULL; + Py_XDECREF(self->checker); + self->checker = NULL; + return 0; + } + if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "restype must be a type, a callable, or None"); + return -1; + } + Py_XDECREF(self->checker); + Py_XDECREF(self->restype); + Py_INCREF(ob); + self->restype = ob; + self->checker = PyObject_GetAttrString(ob, "_check_retval_"); + if (self->checker == NULL) + PyErr_Clear(); + return 0; } static PyObject * PyCFuncPtr_get_restype(PyCFuncPtrObject *self) { - StgDictObject *dict; - if (self->restype) { - Py_INCREF(self->restype); - return self->restype; - } - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ - if (dict->restype) { - Py_INCREF(dict->restype); - return dict->restype; - } else { - Py_INCREF(Py_None); - return Py_None; - } + StgDictObject *dict; + if (self->restype) { + Py_INCREF(self->restype); + return self->restype; + } + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ + if (dict->restype) { + Py_INCREF(dict->restype); + return dict->restype; + } else { + Py_INCREF(Py_None); + return Py_None; + } } static int PyCFuncPtr_set_argtypes(PyCFuncPtrObject *self, PyObject *ob) { - PyObject *converters; - - if (ob == NULL || ob == Py_None) { - Py_XDECREF(self->converters); - self->converters = NULL; - Py_XDECREF(self->argtypes); - self->argtypes = NULL; - } else { - converters = converters_from_argtypes(ob); - if (!converters) - return -1; - Py_XDECREF(self->converters); - self->converters = converters; - Py_XDECREF(self->argtypes); - Py_INCREF(ob); - self->argtypes = ob; - } - return 0; + PyObject *converters; + + if (ob == NULL || ob == Py_None) { + Py_XDECREF(self->converters); + self->converters = NULL; + Py_XDECREF(self->argtypes); + self->argtypes = NULL; + } else { + converters = converters_from_argtypes(ob); + if (!converters) + return -1; + Py_XDECREF(self->converters); + self->converters = converters; + Py_XDECREF(self->argtypes); + Py_INCREF(ob); + self->argtypes = ob; + } + return 0; } static PyObject * PyCFuncPtr_get_argtypes(PyCFuncPtrObject *self) { - StgDictObject *dict; - if (self->argtypes) { - Py_INCREF(self->argtypes); - return self->argtypes; - } - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ - if (dict->argtypes) { - Py_INCREF(dict->argtypes); - return dict->argtypes; - } else { - Py_INCREF(Py_None); - return Py_None; - } + StgDictObject *dict; + if (self->argtypes) { + Py_INCREF(self->argtypes); + return self->argtypes; + } + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ + if (dict->argtypes) { + Py_INCREF(dict->argtypes); + return dict->argtypes; + } else { + Py_INCREF(Py_None); + return Py_None; + } } static PyGetSetDef PyCFuncPtr_getsets[] = { - { "errcheck", (getter)PyCFuncPtr_get_errcheck, (setter)PyCFuncPtr_set_errcheck, - "a function to check for errors", NULL }, - { "restype", (getter)PyCFuncPtr_get_restype, (setter)PyCFuncPtr_set_restype, - "specify the result type", NULL }, - { "argtypes", (getter)PyCFuncPtr_get_argtypes, - (setter)PyCFuncPtr_set_argtypes, - "specify the argument types", NULL }, - { NULL, NULL } + { "errcheck", (getter)PyCFuncPtr_get_errcheck, (setter)PyCFuncPtr_set_errcheck, + "a function to check for errors", NULL }, + { "restype", (getter)PyCFuncPtr_get_restype, (setter)PyCFuncPtr_set_restype, + "specify the result type", NULL }, + { "argtypes", (getter)PyCFuncPtr_get_argtypes, + (setter)PyCFuncPtr_set_argtypes, + "specify the argument types", NULL }, + { NULL, NULL } }; #ifdef MS_WIN32 static PPROC FindAddress(void *handle, char *name, PyObject *type) { #ifdef MS_WIN64 - /* win64 has no stdcall calling conv, so it should - also not have the name mangling of it. - */ - return (PPROC)GetProcAddress(handle, name); + /* win64 has no stdcall calling conv, so it should + also not have the name mangling of it. + */ + return (PPROC)GetProcAddress(handle, name); #else - PPROC address; - char *mangled_name; - int i; - StgDictObject *dict; - - address = (PPROC)GetProcAddress(handle, name); - if (address) - return address; - if (((size_t)name & ~0xFFFF) == 0) { - return NULL; - } - - dict = PyType_stgdict((PyObject *)type); - /* It should not happen that dict is NULL, but better be safe */ - if (dict==NULL || dict->flags & FUNCFLAG_CDECL) - return address; - - /* for stdcall, try mangled names: - funcname -> _funcname@<n> - where n is 0, 4, 8, 12, ..., 128 - */ - mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */ - if (!mangled_name) - return NULL; - for (i = 0; i < 32; ++i) { - sprintf(mangled_name, "_%s@%d", name, i*4); - address = (PPROC)GetProcAddress(handle, mangled_name); - if (address) - return address; - } - return NULL; + PPROC address; + char *mangled_name; + int i; + StgDictObject *dict; + + address = (PPROC)GetProcAddress(handle, name); + if (address) + return address; + if (((size_t)name & ~0xFFFF) == 0) { + return NULL; + } + + dict = PyType_stgdict((PyObject *)type); + /* It should not happen that dict is NULL, but better be safe */ + if (dict==NULL || dict->flags & FUNCFLAG_CDECL) + return address; + + /* for stdcall, try mangled names: + funcname -> _funcname@<n> + where n is 0, 4, 8, 12, ..., 128 + */ + mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */ + if (!mangled_name) + return NULL; + for (i = 0; i < 32; ++i) { + sprintf(mangled_name, "_%s@%d", name, i*4); + address = (PPROC)GetProcAddress(handle, mangled_name); + if (address) + return address; + } + return NULL; #endif } #endif @@ -3051,227 +3051,227 @@ static PPROC FindAddress(void *handle, char *name, PyObject *type) static int _check_outarg_type(PyObject *arg, Py_ssize_t index) { - StgDictObject *dict; + StgDictObject *dict; - if (PyCPointerTypeObject_Check(arg)) - return 1; + if (PyCPointerTypeObject_Check(arg)) + return 1; - if (PyCArrayTypeObject_Check(arg)) - return 1; + if (PyCArrayTypeObject_Check(arg)) + return 1; - dict = PyType_stgdict(arg); - if (dict - /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ - && PyUnicode_Check(dict->proto) + dict = PyType_stgdict(arg); + if (dict + /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ + && PyUnicode_Check(dict->proto) /* We only allow c_void_p, c_char_p and c_wchar_p as a simple output parameter type */ - && (strchr("PzZ", _PyUnicode_AsString(dict->proto)[0]))) { - return 1; - } - - PyErr_Format(PyExc_TypeError, - "'out' parameter %d must be a pointer type, not %s", - Py_SAFE_DOWNCAST(index, Py_ssize_t, int), - PyType_Check(arg) ? - ((PyTypeObject *)arg)->tp_name : - Py_TYPE(arg)->tp_name); - return 0; + && (strchr("PzZ", _PyUnicode_AsString(dict->proto)[0]))) { + return 1; + } + + PyErr_Format(PyExc_TypeError, + "'out' parameter %d must be a pointer type, not %s", + Py_SAFE_DOWNCAST(index, Py_ssize_t, int), + PyType_Check(arg) ? + ((PyTypeObject *)arg)->tp_name : + Py_TYPE(arg)->tp_name); + return 0; } /* Returns 1 on success, 0 on error */ static int _validate_paramflags(PyTypeObject *type, PyObject *paramflags) { - Py_ssize_t i, len; - StgDictObject *dict; - PyObject *argtypes; - - dict = PyType_stgdict((PyObject *)type); - assert(dict); /* Cannot be NULL. 'type' is a PyCFuncPtr type. */ - argtypes = dict->argtypes; - - if (paramflags == NULL || dict->argtypes == NULL) - return 1; - - if (!PyTuple_Check(paramflags)) { - PyErr_SetString(PyExc_TypeError, - "paramflags must be a tuple or None"); - return 0; - } - - len = PyTuple_GET_SIZE(paramflags); - if (len != PyTuple_GET_SIZE(dict->argtypes)) { - PyErr_SetString(PyExc_ValueError, - "paramflags must have the same length as argtypes"); - return 0; - } - - for (i = 0; i < len; ++i) { - PyObject *item = PyTuple_GET_ITEM(paramflags, i); - int flag; - char *name; - PyObject *defval; - PyObject *typ; - if (!PyArg_ParseTuple(item, "i|ZO", &flag, &name, &defval)) { - PyErr_SetString(PyExc_TypeError, - "paramflags must be a sequence of (int [,string [,value]]) tuples"); - return 0; - } - typ = PyTuple_GET_ITEM(argtypes, i); - switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { - case 0: - case PARAMFLAG_FIN: - case PARAMFLAG_FIN | PARAMFLAG_FLCID: - case PARAMFLAG_FIN | PARAMFLAG_FOUT: - break; - case PARAMFLAG_FOUT: - if (!_check_outarg_type(typ, i+1)) - return 0; - break; - default: - PyErr_Format(PyExc_TypeError, - "paramflag value %d not supported", - flag); - return 0; - } - } - return 1; + Py_ssize_t i, len; + StgDictObject *dict; + PyObject *argtypes; + + dict = PyType_stgdict((PyObject *)type); + assert(dict); /* Cannot be NULL. 'type' is a PyCFuncPtr type. */ + argtypes = dict->argtypes; + + if (paramflags == NULL || dict->argtypes == NULL) + return 1; + + if (!PyTuple_Check(paramflags)) { + PyErr_SetString(PyExc_TypeError, + "paramflags must be a tuple or None"); + return 0; + } + + len = PyTuple_GET_SIZE(paramflags); + if (len != PyTuple_GET_SIZE(dict->argtypes)) { + PyErr_SetString(PyExc_ValueError, + "paramflags must have the same length as argtypes"); + return 0; + } + + for (i = 0; i < len; ++i) { + PyObject *item = PyTuple_GET_ITEM(paramflags, i); + int flag; + char *name; + PyObject *defval; + PyObject *typ; + if (!PyArg_ParseTuple(item, "i|ZO", &flag, &name, &defval)) { + PyErr_SetString(PyExc_TypeError, + "paramflags must be a sequence of (int [,string [,value]]) tuples"); + return 0; + } + typ = PyTuple_GET_ITEM(argtypes, i); + switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { + case 0: + case PARAMFLAG_FIN: + case PARAMFLAG_FIN | PARAMFLAG_FLCID: + case PARAMFLAG_FIN | PARAMFLAG_FOUT: + break; + case PARAMFLAG_FOUT: + if (!_check_outarg_type(typ, i+1)) + return 0; + break; + default: + PyErr_Format(PyExc_TypeError, + "paramflag value %d not supported", + flag); + return 0; + } + } + return 1; } static int _get_name(PyObject *obj, char **pname) { #ifdef MS_WIN32 - if (PyLong_Check(obj)) { - /* We have to use MAKEINTRESOURCEA for Windows CE. - Works on Windows as well, of course. - */ - *pname = MAKEINTRESOURCEA(PyLong_AsUnsignedLongMask(obj) & 0xFFFF); - return 1; - } + if (PyLong_Check(obj)) { + /* We have to use MAKEINTRESOURCEA for Windows CE. + Works on Windows as well, of course. + */ + *pname = MAKEINTRESOURCEA(PyLong_AsUnsignedLongMask(obj) & 0xFFFF); + return 1; + } #endif - if (PyBytes_Check(obj)) { - *pname = PyBytes_AS_STRING(obj); - return *pname ? 1 : 0; - } - if (PyUnicode_Check(obj)) { - *pname = _PyUnicode_AsString(obj); - return *pname ? 1 : 0; - } - PyErr_SetString(PyExc_TypeError, - "function name must be string or integer"); - return 0; + if (PyBytes_Check(obj)) { + *pname = PyBytes_AS_STRING(obj); + return *pname ? 1 : 0; + } + if (PyUnicode_Check(obj)) { + *pname = _PyUnicode_AsString(obj); + return *pname ? 1 : 0; + } + PyErr_SetString(PyExc_TypeError, + "function name must be string or integer"); + return 0; } static PyObject * PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds) { - char *name; - int (* address)(void); - PyObject *dll; - PyObject *obj; - PyCFuncPtrObject *self; - void *handle; - PyObject *paramflags = NULL; - - if (!PyArg_ParseTuple(args, "(O&O)|O", _get_name, &name, &dll, ¶mflags)) - return NULL; - if (paramflags == Py_None) - paramflags = NULL; - - obj = PyObject_GetAttrString(dll, "_handle"); - if (!obj) - return NULL; - if (!PyLong_Check(obj)) { - PyErr_SetString(PyExc_TypeError, - "the _handle attribute of the second argument must be an integer"); - Py_DECREF(obj); - return NULL; - } - handle = (void *)PyLong_AsVoidPtr(obj); - Py_DECREF(obj); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_ValueError, - "could not convert the _handle attribute to a pointer"); - return NULL; - } + char *name; + int (* address)(void); + PyObject *dll; + PyObject *obj; + PyCFuncPtrObject *self; + void *handle; + PyObject *paramflags = NULL; + + if (!PyArg_ParseTuple(args, "(O&O)|O", _get_name, &name, &dll, ¶mflags)) + return NULL; + if (paramflags == Py_None) + paramflags = NULL; + + obj = PyObject_GetAttrString(dll, "_handle"); + if (!obj) + return NULL; + if (!PyLong_Check(obj)) { + PyErr_SetString(PyExc_TypeError, + "the _handle attribute of the second argument must be an integer"); + Py_DECREF(obj); + return NULL; + } + handle = (void *)PyLong_AsVoidPtr(obj); + Py_DECREF(obj); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "could not convert the _handle attribute to a pointer"); + return NULL; + } #ifdef MS_WIN32 - address = FindAddress(handle, name, (PyObject *)type); - if (!address) { - if (!IS_INTRESOURCE(name)) - PyErr_Format(PyExc_AttributeError, - "function '%s' not found", - name); - else - PyErr_Format(PyExc_AttributeError, - "function ordinal %d not found", - (WORD)(size_t)name); - return NULL; - } + address = FindAddress(handle, name, (PyObject *)type); + if (!address) { + if (!IS_INTRESOURCE(name)) + PyErr_Format(PyExc_AttributeError, + "function '%s' not found", + name); + else + PyErr_Format(PyExc_AttributeError, + "function ordinal %d not found", + (WORD)(size_t)name); + return NULL; + } #else - address = (PPROC)ctypes_dlsym(handle, name); - if (!address) { + address = (PPROC)ctypes_dlsym(handle, name); + if (!address) { #ifdef __CYGWIN__ /* dlerror() isn't very helpful on cygwin */ - PyErr_Format(PyExc_AttributeError, - "function '%s' not found (%s) ", - name); + PyErr_Format(PyExc_AttributeError, + "function '%s' not found (%s) ", + name); #else - PyErr_SetString(PyExc_AttributeError, ctypes_dlerror()); + PyErr_SetString(PyExc_AttributeError, ctypes_dlerror()); #endif - return NULL; - } + return NULL; + } #endif - if (!_validate_paramflags(type, paramflags)) - return NULL; + if (!_validate_paramflags(type, paramflags)) + return NULL; - self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); - if (!self) - return NULL; + self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); + if (!self) + return NULL; - Py_XINCREF(paramflags); - self->paramflags = paramflags; + Py_XINCREF(paramflags); + self->paramflags = paramflags; - *(void **)self->b_ptr = address; + *(void **)self->b_ptr = address; - Py_INCREF((PyObject *)dll); /* for KeepRef */ - if (-1 == KeepRef((CDataObject *)self, 0, dll)) { - Py_DECREF((PyObject *)self); - return NULL; - } + Py_INCREF((PyObject *)dll); /* for KeepRef */ + if (-1 == KeepRef((CDataObject *)self, 0, dll)) { + Py_DECREF((PyObject *)self); + return NULL; + } - Py_INCREF(self); - self->callable = (PyObject *)self; - return (PyObject *)self; + Py_INCREF(self); + self->callable = (PyObject *)self; + return (PyObject *)self; } #ifdef MS_WIN32 static PyObject * PyCFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyCFuncPtrObject *self; - int index; - char *name = NULL; - PyObject *paramflags = NULL; - GUID *iid = NULL; - Py_ssize_t iid_len = 0; - - if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, ¶mflags, &iid, &iid_len)) - return NULL; - if (paramflags == Py_None) - paramflags = NULL; - - if (!_validate_paramflags(type, paramflags)) - return NULL; - - self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); - self->index = index + 0x1000; - Py_XINCREF(paramflags); - self->paramflags = paramflags; - if (iid_len == sizeof(GUID)) - self->iid = iid; - return (PyObject *)self; + PyCFuncPtrObject *self; + int index; + char *name = NULL; + PyObject *paramflags = NULL; + GUID *iid = NULL; + Py_ssize_t iid_len = 0; + + if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, ¶mflags, &iid, &iid_len)) + return NULL; + if (paramflags == Py_None) + paramflags = NULL; + + if (!_validate_paramflags(type, paramflags)) + return NULL; + + self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); + self->index = index + 0x1000; + Py_XINCREF(paramflags); + self->paramflags = paramflags; + if (iid_len == sizeof(GUID)) + self->iid = iid; + return (PyObject *)self; } #endif @@ -3291,90 +3291,90 @@ PyCFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds) static PyObject * PyCFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyCFuncPtrObject *self; - PyObject *callable; - StgDictObject *dict; - CThunkObject *thunk; + PyCFuncPtrObject *self; + PyObject *callable; + StgDictObject *dict; + CThunkObject *thunk; - if (PyTuple_GET_SIZE(args) == 0) - return GenericPyCData_new(type, args, kwds); + if (PyTuple_GET_SIZE(args) == 0) + return GenericPyCData_new(type, args, kwds); - if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0))) - return PyCFuncPtr_FromDll(type, args, kwds); + if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0))) + return PyCFuncPtr_FromDll(type, args, kwds); #ifdef MS_WIN32 - if (2 <= PyTuple_GET_SIZE(args) && PyLong_Check(PyTuple_GET_ITEM(args, 0))) - return PyCFuncPtr_FromVtblIndex(type, args, kwds); + if (2 <= PyTuple_GET_SIZE(args) && PyLong_Check(PyTuple_GET_ITEM(args, 0))) + return PyCFuncPtr_FromVtblIndex(type, args, kwds); #endif - if (1 == PyTuple_GET_SIZE(args) - && (PyLong_Check(PyTuple_GET_ITEM(args, 0)))) { - CDataObject *ob; - void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0)); - if (ptr == NULL && PyErr_Occurred()) - return NULL; - ob = (CDataObject *)GenericPyCData_new(type, args, kwds); - if (ob == NULL) - return NULL; - *(void **)ob->b_ptr = ptr; - return (PyObject *)ob; - } - - if (!PyArg_ParseTuple(args, "O", &callable)) - return NULL; - if (!PyCallable_Check(callable)) { - PyErr_SetString(PyExc_TypeError, - "argument must be callable or integer function address"); - return NULL; - } - - /* XXX XXX This would allow to pass additional options. For COM - method *implementations*, we would probably want different - behaviour than in 'normal' callback functions: return a HRESULT if - an exception occurrs in the callback, and print the traceback not - only on the console, but also to OutputDebugString() or something - like that. - */ + if (1 == PyTuple_GET_SIZE(args) + && (PyLong_Check(PyTuple_GET_ITEM(args, 0)))) { + CDataObject *ob; + void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0)); + if (ptr == NULL && PyErr_Occurred()) + return NULL; + ob = (CDataObject *)GenericPyCData_new(type, args, kwds); + if (ob == NULL) + return NULL; + *(void **)ob->b_ptr = ptr; + return (PyObject *)ob; + } + + if (!PyArg_ParseTuple(args, "O", &callable)) + return NULL; + if (!PyCallable_Check(callable)) { + PyErr_SetString(PyExc_TypeError, + "argument must be callable or integer function address"); + return NULL; + } + + /* XXX XXX This would allow to pass additional options. For COM + method *implementations*, we would probably want different + behaviour than in 'normal' callback functions: return a HRESULT if + an exception occurrs in the callback, and print the traceback not + only on the console, but also to OutputDebugString() or something + like that. + */ /* - if (kwds && PyDict_GetItemString(kwds, "options")) { - ... - } + if (kwds && PyDict_GetItemString(kwds, "options")) { + ... + } */ - dict = PyType_stgdict((PyObject *)type); - /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */ - if (!dict || !dict->argtypes) { - PyErr_SetString(PyExc_TypeError, - "cannot construct instance of this class:" - " no argtypes"); - return NULL; - } - - thunk = _ctypes_alloc_callback(callable, - dict->argtypes, - dict->restype, - dict->flags); - if (!thunk) - return NULL; - - self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); - if (self == NULL) { - Py_DECREF(thunk); - return NULL; - } - - Py_INCREF(callable); - self->callable = callable; - - self->thunk = thunk; - *(void **)self->b_ptr = (void *)thunk->pcl; - - Py_INCREF((PyObject *)thunk); /* for KeepRef */ - if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) { - Py_DECREF((PyObject *)self); - return NULL; - } - return (PyObject *)self; + dict = PyType_stgdict((PyObject *)type); + /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */ + if (!dict || !dict->argtypes) { + PyErr_SetString(PyExc_TypeError, + "cannot construct instance of this class:" + " no argtypes"); + return NULL; + } + + thunk = _ctypes_alloc_callback(callable, + dict->argtypes, + dict->restype, + dict->flags); + if (!thunk) + return NULL; + + self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); + if (self == NULL) { + Py_DECREF(thunk); + return NULL; + } + + Py_INCREF(callable); + self->callable = callable; + + self->thunk = thunk; + *(void **)self->b_ptr = (void *)thunk->pcl; + + Py_INCREF((PyObject *)thunk); /* for KeepRef */ + if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) { + Py_DECREF((PyObject *)self); + return NULL; + } + return (PyObject *)self; } @@ -3384,54 +3384,54 @@ PyCFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds) static PyObject * _byref(PyObject *obj) { - PyCArgObject *parg; - if (!CDataObject_Check(obj)) { - PyErr_SetString(PyExc_TypeError, - "expected CData instance"); - return NULL; - } - - parg = PyCArgObject_new(); - if (parg == NULL) { - Py_DECREF(obj); - return NULL; - } - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - parg->obj = obj; - parg->value.p = ((CDataObject *)obj)->b_ptr; - return (PyObject *)parg; + PyCArgObject *parg; + if (!CDataObject_Check(obj)) { + PyErr_SetString(PyExc_TypeError, + "expected CData instance"); + return NULL; + } + + parg = PyCArgObject_new(); + if (parg == NULL) { + Py_DECREF(obj); + return NULL; + } + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + parg->obj = obj; + parg->value.p = ((CDataObject *)obj)->b_ptr; + return (PyObject *)parg; } static PyObject * _get_arg(int *pindex, PyObject *name, PyObject *defval, PyObject *inargs, PyObject *kwds) { - PyObject *v; - - if (*pindex < PyTuple_GET_SIZE(inargs)) { - v = PyTuple_GET_ITEM(inargs, *pindex); - ++*pindex; - Py_INCREF(v); - return v; - } - if (kwds && (v = PyDict_GetItem(kwds, name))) { - ++*pindex; - Py_INCREF(v); - return v; - } - if (defval) { - Py_INCREF(defval); - return defval; - } - /* we can't currently emit a better error message */ - if (name) - PyErr_Format(PyExc_TypeError, - "required argument '%S' missing", name); - else - PyErr_Format(PyExc_TypeError, - "not enough arguments"); - return NULL; + PyObject *v; + + if (*pindex < PyTuple_GET_SIZE(inargs)) { + v = PyTuple_GET_ITEM(inargs, *pindex); + ++*pindex; + Py_INCREF(v); + return v; + } + if (kwds && (v = PyDict_GetItem(kwds, name))) { + ++*pindex; + Py_INCREF(v); + return v; + } + if (defval) { + Py_INCREF(defval); + return defval; + } + /* we can't currently emit a better error message */ + if (name) + PyErr_Format(PyExc_TypeError, + "required argument '%S' missing", name); + else + PyErr_Format(PyExc_TypeError, + "not enough arguments"); + return NULL; } /* @@ -3454,166 +3454,166 @@ _get_arg(int *pindex, PyObject *name, PyObject *defval, PyObject *inargs, PyObje */ static PyObject * _build_callargs(PyCFuncPtrObject *self, PyObject *argtypes, - PyObject *inargs, PyObject *kwds, - int *poutmask, int *pinoutmask, unsigned int *pnumretvals) + PyObject *inargs, PyObject *kwds, + int *poutmask, int *pinoutmask, unsigned int *pnumretvals) { - PyObject *paramflags = self->paramflags; - PyObject *callargs; - StgDictObject *dict; - Py_ssize_t i, len; - int inargs_index = 0; - /* It's a little bit difficult to determine how many arguments the - function call requires/accepts. For simplicity, we count the consumed - args and compare this to the number of supplied args. */ - Py_ssize_t actual_args; - - *poutmask = 0; - *pinoutmask = 0; - *pnumretvals = 0; - - /* Trivial cases, where we either return inargs itself, or a slice of it. */ - if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) { + PyObject *paramflags = self->paramflags; + PyObject *callargs; + StgDictObject *dict; + Py_ssize_t i, len; + int inargs_index = 0; + /* It's a little bit difficult to determine how many arguments the + function call requires/accepts. For simplicity, we count the consumed + args and compare this to the number of supplied args. */ + Py_ssize_t actual_args; + + *poutmask = 0; + *pinoutmask = 0; + *pnumretvals = 0; + + /* Trivial cases, where we either return inargs itself, or a slice of it. */ + if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) { #ifdef MS_WIN32 - if (self->index) - return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs)); + if (self->index) + return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs)); #endif - Py_INCREF(inargs); - return inargs; - } + Py_INCREF(inargs); + return inargs; + } - len = PyTuple_GET_SIZE(argtypes); - callargs = PyTuple_New(len); /* the argument tuple we build */ - if (callargs == NULL) - return NULL; + len = PyTuple_GET_SIZE(argtypes); + callargs = PyTuple_New(len); /* the argument tuple we build */ + if (callargs == NULL) + return NULL; #ifdef MS_WIN32 - /* For a COM method, skip the first arg */ - if (self->index) { - inargs_index = 1; - } + /* For a COM method, skip the first arg */ + if (self->index) { + inargs_index = 1; + } #endif - for (i = 0; i < len; ++i) { - PyObject *item = PyTuple_GET_ITEM(paramflags, i); - PyObject *ob; - int flag; - PyObject *name = NULL; - PyObject *defval = NULL; - - /* This way seems to be ~2 us faster than the PyArg_ParseTuple - calls below. */ - /* We HAVE already checked that the tuple can be parsed with "i|ZO", so... */ - Py_ssize_t tsize = PyTuple_GET_SIZE(item); - flag = PyLong_AS_LONG(PyTuple_GET_ITEM(item, 0)); - name = tsize > 1 ? PyTuple_GET_ITEM(item, 1) : NULL; - defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL; - - switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { - case PARAMFLAG_FIN | PARAMFLAG_FLCID: - /* ['in', 'lcid'] parameter. Always taken from defval, - if given, else the integer 0. */ - if (defval == NULL) { - defval = PyLong_FromLong(0); - if (defval == NULL) - goto error; - } else - Py_INCREF(defval); - PyTuple_SET_ITEM(callargs, i, defval); - break; - case (PARAMFLAG_FIN | PARAMFLAG_FOUT): - *pinoutmask |= (1 << i); /* mark as inout arg */ - (*pnumretvals)++; - /* fall through to PARAMFLAG_FIN... */ - case 0: - case PARAMFLAG_FIN: - /* 'in' parameter. Copy it from inargs. */ - ob =_get_arg(&inargs_index, name, defval, inargs, kwds); - if (ob == NULL) - goto error; - PyTuple_SET_ITEM(callargs, i, ob); - break; - case PARAMFLAG_FOUT: - /* XXX Refactor this code into a separate function. */ - /* 'out' parameter. - argtypes[i] must be a POINTER to a c type. - - Cannot by supplied in inargs, but a defval will be used - if available. XXX Should we support getting it from kwds? - */ - if (defval) { - /* XXX Using mutable objects as defval will - make the function non-threadsafe, unless we - copy the object in each invocation */ - Py_INCREF(defval); - PyTuple_SET_ITEM(callargs, i, defval); - *poutmask |= (1 << i); /* mark as out arg */ - (*pnumretvals)++; - break; - } - ob = PyTuple_GET_ITEM(argtypes, i); - dict = PyType_stgdict(ob); - if (dict == NULL) { - /* Cannot happen: _validate_paramflags() - would not accept such an object */ - PyErr_Format(PyExc_RuntimeError, - "NULL stgdict unexpected"); - goto error; - } - if (PyUnicode_Check(dict->proto)) { - PyErr_Format( - PyExc_TypeError, - "%s 'out' parameter must be passed as default value", - ((PyTypeObject *)ob)->tp_name); - goto error; - } - if (PyCArrayTypeObject_Check(ob)) - ob = PyObject_CallObject(ob, NULL); - else - /* Create an instance of the pointed-to type */ - ob = PyObject_CallObject(dict->proto, NULL); - /* - XXX Is the following correct any longer? - We must not pass a byref() to the array then but - the array instance itself. Then, we cannot retrive - the result from the PyCArgObject. - */ - if (ob == NULL) - goto error; - /* The .from_param call that will ocurr later will pass this - as a byref parameter. */ - PyTuple_SET_ITEM(callargs, i, ob); - *poutmask |= (1 << i); /* mark as out arg */ - (*pnumretvals)++; - break; - default: - PyErr_Format(PyExc_ValueError, - "paramflag %d not yet implemented", flag); - goto error; - break; - } - } - - /* We have counted the arguments we have consumed in 'inargs_index'. This - must be the same as len(inargs) + len(kwds), otherwise we have - either too much or not enough arguments. */ - - actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_Size(kwds) : 0); - if (actual_args != inargs_index) { - /* When we have default values or named parameters, this error - message is misleading. See unittests/test_paramflags.py - */ - PyErr_Format(PyExc_TypeError, - "call takes exactly %d arguments (%zd given)", - inargs_index, actual_args); - goto error; - } - - /* outmask is a bitmask containing indexes into callargs. Items at - these indexes contain values to return. - */ - return callargs; + for (i = 0; i < len; ++i) { + PyObject *item = PyTuple_GET_ITEM(paramflags, i); + PyObject *ob; + int flag; + PyObject *name = NULL; + PyObject *defval = NULL; + + /* This way seems to be ~2 us faster than the PyArg_ParseTuple + calls below. */ + /* We HAVE already checked that the tuple can be parsed with "i|ZO", so... */ + Py_ssize_t tsize = PyTuple_GET_SIZE(item); + flag = PyLong_AS_LONG(PyTuple_GET_ITEM(item, 0)); + name = tsize > 1 ? PyTuple_GET_ITEM(item, 1) : NULL; + defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL; + + switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { + case PARAMFLAG_FIN | PARAMFLAG_FLCID: + /* ['in', 'lcid'] parameter. Always taken from defval, + if given, else the integer 0. */ + if (defval == NULL) { + defval = PyLong_FromLong(0); + if (defval == NULL) + goto error; + } else + Py_INCREF(defval); + PyTuple_SET_ITEM(callargs, i, defval); + break; + case (PARAMFLAG_FIN | PARAMFLAG_FOUT): + *pinoutmask |= (1 << i); /* mark as inout arg */ + (*pnumretvals)++; + /* fall through to PARAMFLAG_FIN... */ + case 0: + case PARAMFLAG_FIN: + /* 'in' parameter. Copy it from inargs. */ + ob =_get_arg(&inargs_index, name, defval, inargs, kwds); + if (ob == NULL) + goto error; + PyTuple_SET_ITEM(callargs, i, ob); + break; + case PARAMFLAG_FOUT: + /* XXX Refactor this code into a separate function. */ + /* 'out' parameter. + argtypes[i] must be a POINTER to a c type. + + Cannot by supplied in inargs, but a defval will be used + if available. XXX Should we support getting it from kwds? + */ + if (defval) { + /* XXX Using mutable objects as defval will + make the function non-threadsafe, unless we + copy the object in each invocation */ + Py_INCREF(defval); + PyTuple_SET_ITEM(callargs, i, defval); + *poutmask |= (1 << i); /* mark as out arg */ + (*pnumretvals)++; + break; + } + ob = PyTuple_GET_ITEM(argtypes, i); + dict = PyType_stgdict(ob); + if (dict == NULL) { + /* Cannot happen: _validate_paramflags() + would not accept such an object */ + PyErr_Format(PyExc_RuntimeError, + "NULL stgdict unexpected"); + goto error; + } + if (PyUnicode_Check(dict->proto)) { + PyErr_Format( + PyExc_TypeError, + "%s 'out' parameter must be passed as default value", + ((PyTypeObject *)ob)->tp_name); + goto error; + } + if (PyCArrayTypeObject_Check(ob)) + ob = PyObject_CallObject(ob, NULL); + else + /* Create an instance of the pointed-to type */ + ob = PyObject_CallObject(dict->proto, NULL); + /* + XXX Is the following correct any longer? + We must not pass a byref() to the array then but + the array instance itself. Then, we cannot retrive + the result from the PyCArgObject. + */ + if (ob == NULL) + goto error; + /* The .from_param call that will ocurr later will pass this + as a byref parameter. */ + PyTuple_SET_ITEM(callargs, i, ob); + *poutmask |= (1 << i); /* mark as out arg */ + (*pnumretvals)++; + break; + default: + PyErr_Format(PyExc_ValueError, + "paramflag %d not yet implemented", flag); + goto error; + break; + } + } + + /* We have counted the arguments we have consumed in 'inargs_index'. This + must be the same as len(inargs) + len(kwds), otherwise we have + either too much or not enough arguments. */ + + actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_Size(kwds) : 0); + if (actual_args != inargs_index) { + /* When we have default values or named parameters, this error + message is misleading. See unittests/test_paramflags.py + */ + PyErr_Format(PyExc_TypeError, + "call takes exactly %d arguments (%zd given)", + inargs_index, actual_args); + goto error; + } + + /* outmask is a bitmask containing indexes into callargs. Items at + these indexes contain values to return. + */ + return callargs; error: - Py_DECREF(callargs); - return NULL; + Py_DECREF(callargs); + return NULL; } /* See also: @@ -3626,307 +3626,307 @@ _build_callargs(PyCFuncPtrObject *self, PyObject *argtypes, */ static PyObject * _build_result(PyObject *result, PyObject *callargs, - int outmask, int inoutmask, unsigned int numretvals) + int outmask, int inoutmask, unsigned int numretvals) { - unsigned int i, index; - int bit; - PyObject *tup = NULL; - - if (callargs == NULL) - return result; - if (result == NULL || numretvals == 0) { - Py_DECREF(callargs); - return result; - } - Py_DECREF(result); - - /* tup will not be allocated if numretvals == 1 */ - /* allocate tuple to hold the result */ - if (numretvals > 1) { - tup = PyTuple_New(numretvals); - if (tup == NULL) { - Py_DECREF(callargs); - return NULL; - } - } - - index = 0; - for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) { - PyObject *v; - if (bit & inoutmask) { - v = PyTuple_GET_ITEM(callargs, i); - Py_INCREF(v); - if (numretvals == 1) { - Py_DECREF(callargs); - return v; - } - PyTuple_SET_ITEM(tup, index, v); - index++; - } else if (bit & outmask) { - v = PyTuple_GET_ITEM(callargs, i); - v = PyObject_CallMethod(v, "__ctypes_from_outparam__", NULL); - if (v == NULL || numretvals == 1) { - Py_DECREF(callargs); - return v; - } - PyTuple_SET_ITEM(tup, index, v); - index++; - } - if (index == numretvals) - break; - } - - Py_DECREF(callargs); - return tup; + unsigned int i, index; + int bit; + PyObject *tup = NULL; + + if (callargs == NULL) + return result; + if (result == NULL || numretvals == 0) { + Py_DECREF(callargs); + return result; + } + Py_DECREF(result); + + /* tup will not be allocated if numretvals == 1 */ + /* allocate tuple to hold the result */ + if (numretvals > 1) { + tup = PyTuple_New(numretvals); + if (tup == NULL) { + Py_DECREF(callargs); + return NULL; + } + } + + index = 0; + for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) { + PyObject *v; + if (bit & inoutmask) { + v = PyTuple_GET_ITEM(callargs, i); + Py_INCREF(v); + if (numretvals == 1) { + Py_DECREF(callargs); + return v; + } + PyTuple_SET_ITEM(tup, index, v); + index++; + } else if (bit & outmask) { + v = PyTuple_GET_ITEM(callargs, i); + v = PyObject_CallMethod(v, "__ctypes_from_outparam__", NULL); + if (v == NULL || numretvals == 1) { + Py_DECREF(callargs); + return v; + } + PyTuple_SET_ITEM(tup, index, v); + index++; + } + if (index == numretvals) + break; + } + + Py_DECREF(callargs); + return tup; } static PyObject * PyCFuncPtr_call(PyCFuncPtrObject *self, PyObject *inargs, PyObject *kwds) { - PyObject *restype; - PyObject *converters; - PyObject *checker; - PyObject *argtypes; - StgDictObject *dict = PyObject_stgdict((PyObject *)self); - PyObject *result; - PyObject *callargs; - PyObject *errcheck; + PyObject *restype; + PyObject *converters; + PyObject *checker; + PyObject *argtypes; + StgDictObject *dict = PyObject_stgdict((PyObject *)self); + PyObject *result; + PyObject *callargs; + PyObject *errcheck; #ifdef MS_WIN32 - IUnknown *piunk = NULL; + IUnknown *piunk = NULL; #endif - void *pProc = NULL; + void *pProc = NULL; - int inoutmask; - int outmask; - unsigned int numretvals; + int inoutmask; + int outmask; + unsigned int numretvals; - assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ - restype = self->restype ? self->restype : dict->restype; - converters = self->converters ? self->converters : dict->converters; - checker = self->checker ? self->checker : dict->checker; - argtypes = self->argtypes ? self->argtypes : dict->argtypes; + assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ + restype = self->restype ? self->restype : dict->restype; + converters = self->converters ? self->converters : dict->converters; + checker = self->checker ? self->checker : dict->checker; + argtypes = self->argtypes ? self->argtypes : dict->argtypes; /* later, we probably want to have an errcheck field in stgdict */ - errcheck = self->errcheck /* ? self->errcheck : dict->errcheck */; + errcheck = self->errcheck /* ? self->errcheck : dict->errcheck */; - pProc = *(void **)self->b_ptr; + pProc = *(void **)self->b_ptr; #ifdef MS_WIN32 - if (self->index) { - /* It's a COM method */ - CDataObject *this; - this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */ - if (!this) { - PyErr_SetString(PyExc_ValueError, - "native com method call without 'this' parameter"); - return NULL; - } - if (!CDataObject_Check(this)) { - PyErr_SetString(PyExc_TypeError, - "Expected a COM this pointer as first argument"); - return NULL; - } - /* there should be more checks? No, in Python */ - /* First arg is an pointer to an interface instance */ - if (!this->b_ptr || *(void **)this->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL COM pointer access"); - return NULL; - } - piunk = *(IUnknown **)this->b_ptr; - if (NULL == piunk->lpVtbl) { - PyErr_SetString(PyExc_ValueError, - "COM method call without VTable"); - return NULL; - } - pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000]; - } + if (self->index) { + /* It's a COM method */ + CDataObject *this; + this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */ + if (!this) { + PyErr_SetString(PyExc_ValueError, + "native com method call without 'this' parameter"); + return NULL; + } + if (!CDataObject_Check(this)) { + PyErr_SetString(PyExc_TypeError, + "Expected a COM this pointer as first argument"); + return NULL; + } + /* there should be more checks? No, in Python */ + /* First arg is an pointer to an interface instance */ + if (!this->b_ptr || *(void **)this->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL COM pointer access"); + return NULL; + } + piunk = *(IUnknown **)this->b_ptr; + if (NULL == piunk->lpVtbl) { + PyErr_SetString(PyExc_ValueError, + "COM method call without VTable"); + return NULL; + } + pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000]; + } #endif - callargs = _build_callargs(self, argtypes, - inargs, kwds, - &outmask, &inoutmask, &numretvals); - if (callargs == NULL) - return NULL; - - if (converters) { - int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters), - Py_ssize_t, int); - int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs), - Py_ssize_t, int); - - if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) { - /* For cdecl functions, we allow more actual arguments - than the length of the argtypes tuple. - */ - if (required > actual) { - Py_DECREF(callargs); - PyErr_Format(PyExc_TypeError, - "this function takes at least %d argument%s (%d given)", - required, - required == 1 ? "" : "s", - actual); - return NULL; - } - } else if (required != actual) { - Py_DECREF(callargs); - PyErr_Format(PyExc_TypeError, - "this function takes %d argument%s (%d given)", - required, - required == 1 ? "" : "s", - actual); - return NULL; - } - } - - result = _ctypes_callproc(pProc, - callargs, + callargs = _build_callargs(self, argtypes, + inargs, kwds, + &outmask, &inoutmask, &numretvals); + if (callargs == NULL) + return NULL; + + if (converters) { + int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters), + Py_ssize_t, int); + int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs), + Py_ssize_t, int); + + if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) { + /* For cdecl functions, we allow more actual arguments + than the length of the argtypes tuple. + */ + if (required > actual) { + Py_DECREF(callargs); + PyErr_Format(PyExc_TypeError, + "this function takes at least %d argument%s (%d given)", + required, + required == 1 ? "" : "s", + actual); + return NULL; + } + } else if (required != actual) { + Py_DECREF(callargs); + PyErr_Format(PyExc_TypeError, + "this function takes %d argument%s (%d given)", + required, + required == 1 ? "" : "s", + actual); + return NULL; + } + } + + result = _ctypes_callproc(pProc, + callargs, #ifdef MS_WIN32 - piunk, - self->iid, + piunk, + self->iid, #endif - dict->flags, - converters, - restype, - checker); + dict->flags, + converters, + restype, + checker); /* The 'errcheck' protocol */ - if (result != NULL && errcheck) { - PyObject *v = PyObject_CallFunctionObjArgs(errcheck, - result, - self, - callargs, - NULL); - /* If the errcheck funtion failed, return NULL. - If the errcheck function returned callargs unchanged, - continue normal processing. - If the errcheck function returned something else, - use that as result. - */ - if (v == NULL || v != callargs) { - Py_DECREF(result); - Py_DECREF(callargs); - return v; - } - Py_DECREF(v); - } - - return _build_result(result, callargs, - outmask, inoutmask, numretvals); + if (result != NULL && errcheck) { + PyObject *v = PyObject_CallFunctionObjArgs(errcheck, + result, + self, + callargs, + NULL); + /* If the errcheck funtion failed, return NULL. + If the errcheck function returned callargs unchanged, + continue normal processing. + If the errcheck function returned something else, + use that as result. + */ + if (v == NULL || v != callargs) { + Py_DECREF(result); + Py_DECREF(callargs); + return v; + } + Py_DECREF(v); + } + + return _build_result(result, callargs, + outmask, inoutmask, numretvals); } static int PyCFuncPtr_traverse(PyCFuncPtrObject *self, visitproc visit, void *arg) { - Py_VISIT(self->callable); - Py_VISIT(self->restype); - Py_VISIT(self->checker); - Py_VISIT(self->errcheck); - Py_VISIT(self->argtypes); - Py_VISIT(self->converters); - Py_VISIT(self->paramflags); - Py_VISIT(self->thunk); - return PyCData_traverse((CDataObject *)self, visit, arg); + Py_VISIT(self->callable); + Py_VISIT(self->restype); + Py_VISIT(self->checker); + Py_VISIT(self->errcheck); + Py_VISIT(self->argtypes); + Py_VISIT(self->converters); + Py_VISIT(self->paramflags); + Py_VISIT(self->thunk); + return PyCData_traverse((CDataObject *)self, visit, arg); } static int PyCFuncPtr_clear(PyCFuncPtrObject *self) { - Py_CLEAR(self->callable); - Py_CLEAR(self->restype); - Py_CLEAR(self->checker); - Py_CLEAR(self->errcheck); - Py_CLEAR(self->argtypes); - Py_CLEAR(self->converters); - Py_CLEAR(self->paramflags); - Py_CLEAR(self->thunk); - return PyCData_clear((CDataObject *)self); + Py_CLEAR(self->callable); + Py_CLEAR(self->restype); + Py_CLEAR(self->checker); + Py_CLEAR(self->errcheck); + Py_CLEAR(self->argtypes); + Py_CLEAR(self->converters); + Py_CLEAR(self->paramflags); + Py_CLEAR(self->thunk); + return PyCData_clear((CDataObject *)self); } static void PyCFuncPtr_dealloc(PyCFuncPtrObject *self) { - PyCFuncPtr_clear(self); - Py_TYPE(self)->tp_free((PyObject *)self); + PyCFuncPtr_clear(self); + Py_TYPE(self)->tp_free((PyObject *)self); } static PyObject * PyCFuncPtr_repr(PyCFuncPtrObject *self) { #ifdef MS_WIN32 - if (self->index) - return PyUnicode_FromFormat("<COM method offset %d: %s at %p>", - self->index - 0x1000, - Py_TYPE(self)->tp_name, - self); + if (self->index) + return PyUnicode_FromFormat("<COM method offset %d: %s at %p>", + self->index - 0x1000, + Py_TYPE(self)->tp_name, + self); #endif - return PyUnicode_FromFormat("<%s object at %p>", - Py_TYPE(self)->tp_name, - self); + return PyUnicode_FromFormat("<%s object at %p>", + Py_TYPE(self)->tp_name, + self); } static int PyCFuncPtr_bool(PyCFuncPtrObject *self) { - return ((*(void **)self->b_ptr != NULL) + return ((*(void **)self->b_ptr != NULL) #ifdef MS_WIN32 - || (self->index != 0) + || (self->index != 0) #endif - ); + ); } static PyNumberMethods PyCFuncPtr_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)PyCFuncPtr_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)PyCFuncPtr_bool, /* nb_bool */ }; PyTypeObject PyCFuncPtr_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCFuncPtr", - sizeof(PyCFuncPtrObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)PyCFuncPtr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)PyCFuncPtr_repr, /* tp_repr */ - &PyCFuncPtr_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)PyCFuncPtr_call, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "Function Pointer", /* tp_doc */ - (traverseproc)PyCFuncPtr_traverse, /* tp_traverse */ - (inquiry)PyCFuncPtr_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - PyCFuncPtr_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCFuncPtr_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCFuncPtr", + sizeof(PyCFuncPtrObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)PyCFuncPtr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)PyCFuncPtr_repr, /* tp_repr */ + &PyCFuncPtr_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)PyCFuncPtr_call, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "Function Pointer", /* tp_doc */ + (traverseproc)PyCFuncPtr_traverse, /* tp_traverse */ + (inquiry)PyCFuncPtr_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + PyCFuncPtr_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCFuncPtr_new, /* tp_new */ + 0, /* tp_free */ }; - + /*****************************************************************/ /* Struct_Type @@ -3941,61 +3941,61 @@ PyTypeObject PyCFuncPtr_Type = { */ static int _init_pos_args(PyObject *self, PyTypeObject *type, - PyObject *args, PyObject *kwds, - int index) + PyObject *args, PyObject *kwds, + int index) { - StgDictObject *dict; - PyObject *fields; - int i; - - if (PyType_stgdict((PyObject *)type->tp_base)) { - index = _init_pos_args(self, type->tp_base, - args, kwds, - index); - if (index == -1) - return -1; - } - - dict = PyType_stgdict((PyObject *)type); - fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); - if (fields == NULL) - return index; - - for (i = 0; - i < dict->length && (i+index) < PyTuple_GET_SIZE(args); - ++i) { - PyObject *pair = PySequence_GetItem(fields, i); - PyObject *name, *val; - int res; - if (!pair) - return -1; - name = PySequence_GetItem(pair, 0); - if (!name) { - Py_DECREF(pair); - return -1; - } - val = PyTuple_GET_ITEM(args, i + index); - if (kwds && PyDict_GetItem(kwds, name)) { - char *field = PyBytes_AsString(name); - if (field == NULL) { - PyErr_Clear(); - field = "???"; - } - PyErr_Format(PyExc_TypeError, - "duplicate values for field '%s'", - field); - Py_DECREF(pair); - Py_DECREF(name); - return -1; - } - - res = PyObject_SetAttr(self, name, val); - Py_DECREF(pair); - Py_DECREF(name); - if (res == -1) - return -1; - } - return index + dict->length; + StgDictObject *dict; + PyObject *fields; + int i; + + if (PyType_stgdict((PyObject *)type->tp_base)) { + index = _init_pos_args(self, type->tp_base, + args, kwds, + index); + if (index == -1) + return -1; + } + + dict = PyType_stgdict((PyObject *)type); + fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); + if (fields == NULL) + return index; + + for (i = 0; + i < dict->length && (i+index) < PyTuple_GET_SIZE(args); + ++i) { + PyObject *pair = PySequence_GetItem(fields, i); + PyObject *name, *val; + int res; + if (!pair) + return -1; + name = PySequence_GetItem(pair, 0); + if (!name) { + Py_DECREF(pair); + return -1; + } + val = PyTuple_GET_ITEM(args, i + index); + if (kwds && PyDict_GetItem(kwds, name)) { + char *field = PyBytes_AsString(name); + if (field == NULL) { + PyErr_Clear(); + field = "???"; + } + PyErr_Format(PyExc_TypeError, + "duplicate values for field '%s'", + field); + Py_DECREF(pair); + Py_DECREF(name); + return -1; + } + + res = PyObject_SetAttr(self, name, val); + Py_DECREF(pair); + Py_DECREF(name); + if (res == -1) + return -1; + } + return index + dict->length; } static int @@ -4004,119 +4004,119 @@ Struct_init(PyObject *self, PyObject *args, PyObject *kwds) /* Optimization possible: Store the attribute names _fields_[x][0] * in C accessible fields somewhere ? */ - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_TypeError, - "args not a tuple?"); - return -1; - } - if (PyTuple_GET_SIZE(args)) { - int res = _init_pos_args(self, Py_TYPE(self), - args, kwds, 0); - if (res == -1) - return -1; - if (res < PyTuple_GET_SIZE(args)) { - PyErr_SetString(PyExc_TypeError, - "too many initializers"); - return -1; - } - } - - if (kwds) { - PyObject *key, *value; - Py_ssize_t pos = 0; - while(PyDict_Next(kwds, &pos, &key, &value)) { - if (-1 == PyObject_SetAttr(self, key, value)) - return -1; - } - } - return 0; + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "args not a tuple?"); + return -1; + } + if (PyTuple_GET_SIZE(args)) { + int res = _init_pos_args(self, Py_TYPE(self), + args, kwds, 0); + if (res == -1) + return -1; + if (res < PyTuple_GET_SIZE(args)) { + PyErr_SetString(PyExc_TypeError, + "too many initializers"); + return -1; + } + } + + if (kwds) { + PyObject *key, *value; + Py_ssize_t pos = 0; + while(PyDict_Next(kwds, &pos, &key, &value)) { + if (-1 == PyObject_SetAttr(self, key, value)) + return -1; + } + } + return 0; } static PyTypeObject Struct_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.Structure", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "Structure base class", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - Struct_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.Structure", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "Structure base class", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + Struct_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; static PyTypeObject Union_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.Union", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "Union base class", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - Struct_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.Union", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "Union base class", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + Struct_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCArray_Type @@ -4124,371 +4124,371 @@ static PyTypeObject Union_Type = { static int Array_init(CDataObject *self, PyObject *args, PyObject *kw) { - Py_ssize_t i; - Py_ssize_t n; - - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_TypeError, - "args not a tuple?"); - return -1; - } - n = PyTuple_GET_SIZE(args); - for (i = 0; i < n; ++i) { - PyObject *v; - v = PyTuple_GET_ITEM(args, i); - if (-1 == PySequence_SetItem((PyObject *)self, i, v)) - return -1; - } - return 0; + Py_ssize_t i; + Py_ssize_t n; + + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "args not a tuple?"); + return -1; + } + n = PyTuple_GET_SIZE(args); + for (i = 0; i < n; ++i) { + PyObject *v; + v = PyTuple_GET_ITEM(args, i); + if (-1 == PySequence_SetItem((PyObject *)self, i, v)) + return -1; + } + return 0; } static PyObject * Array_item(PyObject *_self, Py_ssize_t index) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t offset, size; - StgDictObject *stgdict; - - - if (index < 0 || index >= self->b_length) { - PyErr_SetString(PyExc_IndexError, - "invalid index"); - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for array instances */ - /* Would it be clearer if we got the item size from - stgdict->proto's stgdict? - */ - size = stgdict->size / stgdict->length; - offset = index * size; - - return PyCData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self, - index, size, self->b_ptr + offset); + CDataObject *self = (CDataObject *)_self; + Py_ssize_t offset, size; + StgDictObject *stgdict; + + + if (index < 0 || index >= self->b_length) { + PyErr_SetString(PyExc_IndexError, + "invalid index"); + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for array instances */ + /* Would it be clearer if we got the item size from + stgdict->proto's stgdict? + */ + size = stgdict->size / stgdict->length; + offset = index * size; + + return PyCData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self, + index, size, self->b_ptr + offset); } static PyObject * Array_subscript(PyObject *_self, PyObject *item) { - CDataObject *self = (CDataObject *)_self; - - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - - if (i == -1 && PyErr_Occurred()) - return NULL; - if (i < 0) - i += self->b_length; - return Array_item(_self, i); - } - else if PySlice_Check(item) { - StgDictObject *stgdict, *itemdict; - PyObject *proto; - PyObject *np; - Py_ssize_t start, stop, step, slicelen, cur, i; - - if (PySlice_GetIndicesEx((PySliceObject *)item, - self->b_length, &start, &stop, - &step, &slicelen) < 0) { - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for array object instances */ - proto = stgdict->proto; - itemdict = PyType_stgdict(proto); - assert(itemdict); /* proto is the item type of the array, a - ctypes type, so this cannot be NULL */ - - if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - char *ptr = (char *)self->b_ptr; - char *dest; - - if (slicelen <= 0) - return PyBytes_FromStringAndSize("", 0); - if (step == 1) { - return PyBytes_FromStringAndSize(ptr + start, - slicelen); - } - dest = (char *)PyMem_Malloc(slicelen); - - if (dest == NULL) - return PyErr_NoMemory(); - - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - dest[i] = ptr[cur]; - } - - np = PyBytes_FromStringAndSize(dest, slicelen); - PyMem_Free(dest); - return np; - } + CDataObject *self = (CDataObject *)_self; + + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + + if (i == -1 && PyErr_Occurred()) + return NULL; + if (i < 0) + i += self->b_length; + return Array_item(_self, i); + } + else if PySlice_Check(item) { + StgDictObject *stgdict, *itemdict; + PyObject *proto; + PyObject *np; + Py_ssize_t start, stop, step, slicelen, cur, i; + + if (PySlice_GetIndicesEx((PySliceObject *)item, + self->b_length, &start, &stop, + &step, &slicelen) < 0) { + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for array object instances */ + proto = stgdict->proto; + itemdict = PyType_stgdict(proto); + assert(itemdict); /* proto is the item type of the array, a + ctypes type, so this cannot be NULL */ + + if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + char *ptr = (char *)self->b_ptr; + char *dest; + + if (slicelen <= 0) + return PyBytes_FromStringAndSize("", 0); + if (step == 1) { + return PyBytes_FromStringAndSize(ptr + start, + slicelen); + } + dest = (char *)PyMem_Malloc(slicelen); + + if (dest == NULL) + return PyErr_NoMemory(); + + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + dest[i] = ptr[cur]; + } + + np = PyBytes_FromStringAndSize(dest, slicelen); + PyMem_Free(dest); + return np; + } #ifdef CTYPES_UNICODE - if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - wchar_t *ptr = (wchar_t *)self->b_ptr; - wchar_t *dest; - - if (slicelen <= 0) - return PyUnicode_FromUnicode(NULL, 0); - if (step == 1) { - return PyUnicode_FromWideChar(ptr + start, - slicelen); - } - - dest = (wchar_t *)PyMem_Malloc( - slicelen * sizeof(wchar_t)); - - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - dest[i] = ptr[cur]; - } - - np = PyUnicode_FromWideChar(dest, slicelen); - PyMem_Free(dest); - return np; - } + if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + wchar_t *ptr = (wchar_t *)self->b_ptr; + wchar_t *dest; + + if (slicelen <= 0) + return PyUnicode_FromUnicode(NULL, 0); + if (step == 1) { + return PyUnicode_FromWideChar(ptr + start, + slicelen); + } + + dest = (wchar_t *)PyMem_Malloc( + slicelen * sizeof(wchar_t)); + + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + dest[i] = ptr[cur]; + } + + np = PyUnicode_FromWideChar(dest, slicelen); + PyMem_Free(dest); + return np; + } #endif - np = PyList_New(slicelen); - if (np == NULL) - return NULL; - - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - PyObject *v = Array_item(_self, cur); - PyList_SET_ITEM(np, i, v); - } - return np; - } - else { - PyErr_SetString(PyExc_TypeError, - "indices must be integers"); - return NULL; - } + np = PyList_New(slicelen); + if (np == NULL) + return NULL; + + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + PyObject *v = Array_item(_self, cur); + PyList_SET_ITEM(np, i, v); + } + return np; + } + else { + PyErr_SetString(PyExc_TypeError, + "indices must be integers"); + return NULL; + } } static int Array_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t size, offset; - StgDictObject *stgdict; - char *ptr; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Array does not support item deletion"); - return -1; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for array object instances */ - if (index < 0 || index >= stgdict->length) { - PyErr_SetString(PyExc_IndexError, - "invalid index"); - return -1; - } - size = stgdict->size / stgdict->length; - offset = index * size; - ptr = self->b_ptr + offset; - - return PyCData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value, - index, size, ptr); + CDataObject *self = (CDataObject *)_self; + Py_ssize_t size, offset; + StgDictObject *stgdict; + char *ptr; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Array does not support item deletion"); + return -1; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for array object instances */ + if (index < 0 || index >= stgdict->length) { + PyErr_SetString(PyExc_IndexError, + "invalid index"); + return -1; + } + size = stgdict->size / stgdict->length; + offset = index * size; + ptr = self->b_ptr + offset; + + return PyCData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value, + index, size, ptr); } static int Array_ass_subscript(PyObject *_self, PyObject *item, PyObject *value) { - CDataObject *self = (CDataObject *)_self; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Array does not support item deletion"); - return -1; - } - - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) - i += self->b_length; - return Array_ass_item(_self, i, value); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelen, otherlen, i, cur; - - if (PySlice_GetIndicesEx((PySliceObject *)item, - self->b_length, &start, &stop, - &step, &slicelen) < 0) { - return -1; - } - if ((step < 0 && start < stop) || - (step > 0 && start > stop)) - stop = start; - - otherlen = PySequence_Length(value); - if (otherlen != slicelen) { - PyErr_SetString(PyExc_ValueError, - "Can only assign sequence of same size"); - return -1; - } - for (cur = start, i = 0; i < otherlen; cur += step, i++) { - PyObject *item = PySequence_GetItem(value, i); - int result; - if (item == NULL) - return -1; - result = Array_ass_item(_self, cur, item); - Py_DECREF(item); - if (result == -1) - return -1; - } - return 0; - } - else { - PyErr_SetString(PyExc_TypeError, - "indices must be integer"); - return -1; - } + CDataObject *self = (CDataObject *)_self; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Array does not support item deletion"); + return -1; + } + + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) + i += self->b_length; + return Array_ass_item(_self, i, value); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelen, otherlen, i, cur; + + if (PySlice_GetIndicesEx((PySliceObject *)item, + self->b_length, &start, &stop, + &step, &slicelen) < 0) { + return -1; + } + if ((step < 0 && start < stop) || + (step > 0 && start > stop)) + stop = start; + + otherlen = PySequence_Length(value); + if (otherlen != slicelen) { + PyErr_SetString(PyExc_ValueError, + "Can only assign sequence of same size"); + return -1; + } + for (cur = start, i = 0; i < otherlen; cur += step, i++) { + PyObject *item = PySequence_GetItem(value, i); + int result; + if (item == NULL) + return -1; + result = Array_ass_item(_self, cur, item); + Py_DECREF(item); + if (result == -1) + return -1; + } + return 0; + } + else { + PyErr_SetString(PyExc_TypeError, + "indices must be integer"); + return -1; + } } static Py_ssize_t Array_length(PyObject *_self) { - CDataObject *self = (CDataObject *)_self; - return self->b_length; + CDataObject *self = (CDataObject *)_self; + return self->b_length; } static PySequenceMethods Array_as_sequence = { - Array_length, /* sq_length; */ - 0, /* sq_concat; */ - 0, /* sq_repeat; */ - Array_item, /* sq_item; */ - 0, /* sq_slice; */ - Array_ass_item, /* sq_ass_item; */ - 0, /* sq_ass_slice; */ - 0, /* sq_contains; */ - - 0, /* sq_inplace_concat; */ - 0, /* sq_inplace_repeat; */ + Array_length, /* sq_length; */ + 0, /* sq_concat; */ + 0, /* sq_repeat; */ + Array_item, /* sq_item; */ + 0, /* sq_slice; */ + Array_ass_item, /* sq_ass_item; */ + 0, /* sq_ass_slice; */ + 0, /* sq_contains; */ + + 0, /* sq_inplace_concat; */ + 0, /* sq_inplace_repeat; */ }; static PyMappingMethods Array_as_mapping = { - Array_length, - Array_subscript, - Array_ass_subscript, + Array_length, + Array_subscript, + Array_ass_subscript, }; PyTypeObject PyCArray_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.Array", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &Array_as_sequence, /* tp_as_sequence */ - &Array_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)Array_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.Array", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &Array_as_sequence, /* tp_as_sequence */ + &Array_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Array_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; PyObject * PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length) { - static PyObject *cache; - PyObject *key; - PyObject *result; - char name[256]; - PyObject *len; - - if (cache == NULL) { - cache = PyDict_New(); - if (cache == NULL) - return NULL; - } - len = PyLong_FromSsize_t(length); - if (len == NULL) - return NULL; - key = PyTuple_Pack(2, itemtype, len); - Py_DECREF(len); - if (!key) - return NULL; - result = PyDict_GetItemProxy(cache, key); - if (result) { - Py_INCREF(result); - Py_DECREF(key); - return result; - } - - if (!PyType_Check(itemtype)) { - PyErr_SetString(PyExc_TypeError, - "Expected a type object"); - return NULL; - } + static PyObject *cache; + PyObject *key; + PyObject *result; + char name[256]; + PyObject *len; + + if (cache == NULL) { + cache = PyDict_New(); + if (cache == NULL) + return NULL; + } + len = PyLong_FromSsize_t(length); + if (len == NULL) + return NULL; + key = PyTuple_Pack(2, itemtype, len); + Py_DECREF(len); + if (!key) + return NULL; + result = PyDict_GetItemProxy(cache, key); + if (result) { + Py_INCREF(result); + Py_DECREF(key); + return result; + } + + if (!PyType_Check(itemtype)) { + PyErr_SetString(PyExc_TypeError, + "Expected a type object"); + return NULL; + } #ifdef MS_WIN64 - sprintf(name, "%.200s_Array_%Id", - ((PyTypeObject *)itemtype)->tp_name, length); + sprintf(name, "%.200s_Array_%Id", + ((PyTypeObject *)itemtype)->tp_name, length); #else - sprintf(name, "%.200s_Array_%ld", - ((PyTypeObject *)itemtype)->tp_name, (long)length); + sprintf(name, "%.200s_Array_%ld", + ((PyTypeObject *)itemtype)->tp_name, (long)length); #endif - result = PyObject_CallFunction((PyObject *)&PyCArrayType_Type, - "U(O){s:n,s:O}", - name, - &PyCArray_Type, - "_length_", - length, - "_type_", - itemtype - ); - if (result == NULL) { - Py_DECREF(key); - return NULL; - } - if (-1 == PyDict_SetItemProxy(cache, key, result)) { - Py_DECREF(key); - Py_DECREF(result); - return NULL; - } - Py_DECREF(key); - return result; + result = PyObject_CallFunction((PyObject *)&PyCArrayType_Type, + "U(O){s:n,s:O}", + name, + &PyCArray_Type, + "_length_", + length, + "_type_", + itemtype + ); + if (result == NULL) { + Py_DECREF(key); + return NULL; + } + if (-1 == PyDict_SetItemProxy(cache, key, result)) { + Py_DECREF(key); + Py_DECREF(result); + return NULL; + } + Py_DECREF(key); + return result; } - + /******************************************************************/ /* Simple_Type @@ -4497,166 +4497,166 @@ PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length) static int Simple_set_value(CDataObject *self, PyObject *value) { - PyObject *result; - StgDictObject *dict = PyObject_stgdict((PyObject *)self); - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - assert(dict); /* Cannot be NULL for CDataObject instances */ - assert(dict->setfunc); - result = dict->setfunc(self->b_ptr, value, dict->size); - if (!result) - return -1; - - /* consumes the refcount the setfunc returns */ - return KeepRef(self, 0, result); + PyObject *result; + StgDictObject *dict = PyObject_stgdict((PyObject *)self); + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } + assert(dict); /* Cannot be NULL for CDataObject instances */ + assert(dict->setfunc); + result = dict->setfunc(self->b_ptr, value, dict->size); + if (!result) + return -1; + + /* consumes the refcount the setfunc returns */ + return KeepRef(self, 0, result); } static int Simple_init(CDataObject *self, PyObject *args, PyObject *kw) { - PyObject *value = NULL; - if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value)) - return -1; - if (value) - return Simple_set_value(self, value); - return 0; + PyObject *value = NULL; + if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value)) + return -1; + if (value) + return Simple_set_value(self, value); + return 0; } static PyObject * Simple_get_value(CDataObject *self) { - StgDictObject *dict; - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for CDataObject instances */ - assert(dict->getfunc); - return dict->getfunc(self->b_ptr, self->b_size); + StgDictObject *dict; + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for CDataObject instances */ + assert(dict->getfunc); + return dict->getfunc(self->b_ptr, self->b_size); } static PyGetSetDef Simple_getsets[] = { - { "value", (getter)Simple_get_value, (setter)Simple_set_value, - "current value", NULL }, - { NULL, NULL } + { "value", (getter)Simple_get_value, (setter)Simple_set_value, + "current value", NULL }, + { NULL, NULL } }; static PyObject * Simple_from_outparm(PyObject *self, PyObject *args) { - if (_ctypes_simple_instance((PyObject *)Py_TYPE(self))) { - Py_INCREF(self); - return self; - } - /* call stgdict->getfunc */ - return Simple_get_value((CDataObject *)self); + if (_ctypes_simple_instance((PyObject *)Py_TYPE(self))) { + Py_INCREF(self); + return self; + } + /* call stgdict->getfunc */ + return Simple_get_value((CDataObject *)self); } static PyMethodDef Simple_methods[] = { - { "__ctypes_from_outparam__", Simple_from_outparm, METH_NOARGS, }, - { NULL, NULL }, + { "__ctypes_from_outparam__", Simple_from_outparm, METH_NOARGS, }, + { NULL, NULL }, }; static int Simple_bool(CDataObject *self) { - return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size); + return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size); } static PyNumberMethods Simple_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)Simple_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)Simple_bool, /* nb_bool */ }; /* "%s(%s)" % (self.__class__.__name__, self.value) */ static PyObject * Simple_repr(CDataObject *self) { - PyObject *val, *name, *args, *result; - static PyObject *format; - - if (Py_TYPE(self)->tp_base != &Simple_Type) { - return PyUnicode_FromFormat("<%s object at %p>", - Py_TYPE(self)->tp_name, self); - } - - if (format == NULL) { - format = PyUnicode_InternFromString("%s(%r)"); - if (format == NULL) - return NULL; - } - - val = Simple_get_value(self); - if (val == NULL) - return NULL; - - name = PyUnicode_FromString(Py_TYPE(self)->tp_name); - if (name == NULL) { - Py_DECREF(val); - return NULL; - } - - args = PyTuple_Pack(2, name, val); - Py_DECREF(name); - Py_DECREF(val); - if (args == NULL) - return NULL; - - result = PyUnicode_Format(format, args); - Py_DECREF(args); - return result; + PyObject *val, *name, *args, *result; + static PyObject *format; + + if (Py_TYPE(self)->tp_base != &Simple_Type) { + return PyUnicode_FromFormat("<%s object at %p>", + Py_TYPE(self)->tp_name, self); + } + + if (format == NULL) { + format = PyUnicode_InternFromString("%s(%r)"); + if (format == NULL) + return NULL; + } + + val = Simple_get_value(self); + if (val == NULL) + return NULL; + + name = PyUnicode_FromString(Py_TYPE(self)->tp_name); + if (name == NULL) { + Py_DECREF(val); + return NULL; + } + + args = PyTuple_Pack(2, name, val); + Py_DECREF(name); + Py_DECREF(val); + if (args == NULL) + return NULL; + + result = PyUnicode_Format(format, args); + Py_DECREF(args); + return result; } static PyTypeObject Simple_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes._SimpleCData", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)&Simple_repr, /* tp_repr */ - &Simple_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - Simple_methods, /* tp_methods */ - 0, /* tp_members */ - Simple_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)Simple_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes._SimpleCData", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)&Simple_repr, /* tp_repr */ + &Simple_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + Simple_methods, /* tp_methods */ + 0, /* tp_members */ + Simple_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Simple_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCPointer_Type @@ -4664,377 +4664,377 @@ static PyTypeObject Simple_Type = { static PyObject * Pointer_item(PyObject *_self, Py_ssize_t index) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t size; - Py_ssize_t offset; - StgDictObject *stgdict, *itemdict; - PyObject *proto; - - if (*(void **)self->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL pointer access"); - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for pointer object instances */ - - proto = stgdict->proto; - assert(proto); - itemdict = PyType_stgdict(proto); - assert(itemdict); /* proto is the item type of the pointer, a ctypes - type, so this cannot be NULL */ - - size = itemdict->size; - offset = index * itemdict->size; - - return PyCData_get(proto, stgdict->getfunc, (PyObject *)self, - index, size, (*(char **)self->b_ptr) + offset); + CDataObject *self = (CDataObject *)_self; + Py_ssize_t size; + Py_ssize_t offset; + StgDictObject *stgdict, *itemdict; + PyObject *proto; + + if (*(void **)self->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL pointer access"); + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for pointer object instances */ + + proto = stgdict->proto; + assert(proto); + itemdict = PyType_stgdict(proto); + assert(itemdict); /* proto is the item type of the pointer, a ctypes + type, so this cannot be NULL */ + + size = itemdict->size; + offset = index * itemdict->size; + + return PyCData_get(proto, stgdict->getfunc, (PyObject *)self, + index, size, (*(char **)self->b_ptr) + offset); } static int Pointer_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t size; - Py_ssize_t offset; - StgDictObject *stgdict, *itemdict; - PyObject *proto; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Pointer does not support item deletion"); - return -1; - } - - if (*(void **)self->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL pointer access"); - return -1; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL fr pointer instances */ - - proto = stgdict->proto; - assert(proto); - - itemdict = PyType_stgdict(proto); - assert(itemdict); /* Cannot be NULL because the itemtype of a pointer - is always a ctypes type */ - - size = itemdict->size; - offset = index * itemdict->size; - - return PyCData_set((PyObject *)self, proto, stgdict->setfunc, value, - index, size, (*(char **)self->b_ptr) + offset); + CDataObject *self = (CDataObject *)_self; + Py_ssize_t size; + Py_ssize_t offset; + StgDictObject *stgdict, *itemdict; + PyObject *proto; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Pointer does not support item deletion"); + return -1; + } + + if (*(void **)self->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL pointer access"); + return -1; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL fr pointer instances */ + + proto = stgdict->proto; + assert(proto); + + itemdict = PyType_stgdict(proto); + assert(itemdict); /* Cannot be NULL because the itemtype of a pointer + is always a ctypes type */ + + size = itemdict->size; + offset = index * itemdict->size; + + return PyCData_set((PyObject *)self, proto, stgdict->setfunc, value, + index, size, (*(char **)self->b_ptr) + offset); } static PyObject * Pointer_get_contents(CDataObject *self, void *closure) { - StgDictObject *stgdict; - - if (*(void **)self->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL pointer access"); - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL fr pointer instances */ - return PyCData_FromBaseObj(stgdict->proto, - (PyObject *)self, 0, - *(void **)self->b_ptr); + StgDictObject *stgdict; + + if (*(void **)self->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL pointer access"); + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL fr pointer instances */ + return PyCData_FromBaseObj(stgdict->proto, + (PyObject *)self, 0, + *(void **)self->b_ptr); } static int Pointer_set_contents(CDataObject *self, PyObject *value, void *closure) { - StgDictObject *stgdict; - CDataObject *dst; - PyObject *keep; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Pointer does not support item deletion"); - return -1; - } - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL fr pointer instances */ - assert(stgdict->proto); - if (!CDataObject_Check(value) - || 0 == PyObject_IsInstance(value, stgdict->proto)) { - /* XXX PyObject_IsInstance could return -1! */ - PyErr_Format(PyExc_TypeError, - "expected %s instead of %s", - ((PyTypeObject *)(stgdict->proto))->tp_name, - Py_TYPE(value)->tp_name); - return -1; - } - - dst = (CDataObject *)value; - *(void **)self->b_ptr = dst->b_ptr; - - /* - A Pointer instance must keep a the value it points to alive. So, a - pointer instance has b_length set to 2 instead of 1, and we set - 'value' itself as the second item of the b_objects list, additionally. - */ - Py_INCREF(value); - if (-1 == KeepRef(self, 1, value)) - return -1; - - keep = GetKeepedObjects(dst); - Py_INCREF(keep); - return KeepRef(self, 0, keep); + StgDictObject *stgdict; + CDataObject *dst; + PyObject *keep; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Pointer does not support item deletion"); + return -1; + } + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL fr pointer instances */ + assert(stgdict->proto); + if (!CDataObject_Check(value) + || 0 == PyObject_IsInstance(value, stgdict->proto)) { + /* XXX PyObject_IsInstance could return -1! */ + PyErr_Format(PyExc_TypeError, + "expected %s instead of %s", + ((PyTypeObject *)(stgdict->proto))->tp_name, + Py_TYPE(value)->tp_name); + return -1; + } + + dst = (CDataObject *)value; + *(void **)self->b_ptr = dst->b_ptr; + + /* + A Pointer instance must keep a the value it points to alive. So, a + pointer instance has b_length set to 2 instead of 1, and we set + 'value' itself as the second item of the b_objects list, additionally. + */ + Py_INCREF(value); + if (-1 == KeepRef(self, 1, value)) + return -1; + + keep = GetKeepedObjects(dst); + Py_INCREF(keep); + return KeepRef(self, 0, keep); } static PyGetSetDef Pointer_getsets[] = { - { "contents", (getter)Pointer_get_contents, - (setter)Pointer_set_contents, - "the object this pointer points to (read-write)", NULL }, - { NULL, NULL } + { "contents", (getter)Pointer_get_contents, + (setter)Pointer_set_contents, + "the object this pointer points to (read-write)", NULL }, + { NULL, NULL } }; static int Pointer_init(CDataObject *self, PyObject *args, PyObject *kw) { - PyObject *value = NULL; + PyObject *value = NULL; - if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value)) - return -1; - if (value == NULL) - return 0; - return Pointer_set_contents(self, value, NULL); + if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value)) + return -1; + if (value == NULL) + return 0; + return Pointer_set_contents(self, value, NULL); } static PyObject * Pointer_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - StgDictObject *dict = PyType_stgdict((PyObject *)type); - if (!dict || !dict->proto) { - PyErr_SetString(PyExc_TypeError, - "Cannot create instance: has no _type_"); - return NULL; - } - return GenericPyCData_new(type, args, kw); + StgDictObject *dict = PyType_stgdict((PyObject *)type); + if (!dict || !dict->proto) { + PyErr_SetString(PyExc_TypeError, + "Cannot create instance: has no _type_"); + return NULL; + } + return GenericPyCData_new(type, args, kw); } static PyObject * Pointer_subscript(PyObject *_self, PyObject *item) { - CDataObject *self = (CDataObject *)_self; - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - if (i == -1 && PyErr_Occurred()) - return NULL; - return Pointer_item(_self, i); - } - else if (PySlice_Check(item)) { - PySliceObject *slice = (PySliceObject *)item; - Py_ssize_t start, stop, step; - PyObject *np; - StgDictObject *stgdict, *itemdict; - PyObject *proto; - Py_ssize_t i, len, cur; - - /* Since pointers have no length, and we want to apply - different semantics to negative indices than normal - slicing, we have to dissect the slice object ourselves.*/ - if (slice->step == Py_None) { - step = 1; - } - else { - step = PyNumber_AsSsize_t(slice->step, - PyExc_ValueError); - if (step == -1 && PyErr_Occurred()) - return NULL; - if (step == 0) { - PyErr_SetString(PyExc_ValueError, - "slice step cannot be zero"); - return NULL; - } - } - if (slice->start == Py_None) { - if (step < 0) { - PyErr_SetString(PyExc_ValueError, - "slice start is required " - "for step < 0"); - return NULL; - } - start = 0; - } - else { - start = PyNumber_AsSsize_t(slice->start, - PyExc_ValueError); - if (start == -1 && PyErr_Occurred()) - return NULL; - } - if (slice->stop == Py_None) { - PyErr_SetString(PyExc_ValueError, - "slice stop is required"); - return NULL; - } - stop = PyNumber_AsSsize_t(slice->stop, - PyExc_ValueError); - if (stop == -1 && PyErr_Occurred()) - return NULL; - if ((step > 0 && start > stop) || - (step < 0 && start < stop)) - len = 0; - else if (step > 0) - len = (stop - start - 1) / step + 1; - else - len = (stop - start + 1) / step + 1; - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for pointer instances */ - proto = stgdict->proto; - assert(proto); - itemdict = PyType_stgdict(proto); - assert(itemdict); - if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - char *ptr = *(char **)self->b_ptr; - char *dest; - - if (len <= 0) - return PyBytes_FromStringAndSize("", 0); - if (step == 1) { - return PyBytes_FromStringAndSize(ptr + start, - len); - } - dest = (char *)PyMem_Malloc(len); - if (dest == NULL) - return PyErr_NoMemory(); - for (cur = start, i = 0; i < len; cur += step, i++) { - dest[i] = ptr[cur]; - } - np = PyBytes_FromStringAndSize(dest, len); - PyMem_Free(dest); - return np; - } + CDataObject *self = (CDataObject *)_self; + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + if (i == -1 && PyErr_Occurred()) + return NULL; + return Pointer_item(_self, i); + } + else if (PySlice_Check(item)) { + PySliceObject *slice = (PySliceObject *)item; + Py_ssize_t start, stop, step; + PyObject *np; + StgDictObject *stgdict, *itemdict; + PyObject *proto; + Py_ssize_t i, len, cur; + + /* Since pointers have no length, and we want to apply + different semantics to negative indices than normal + slicing, we have to dissect the slice object ourselves.*/ + if (slice->step == Py_None) { + step = 1; + } + else { + step = PyNumber_AsSsize_t(slice->step, + PyExc_ValueError); + if (step == -1 && PyErr_Occurred()) + return NULL; + if (step == 0) { + PyErr_SetString(PyExc_ValueError, + "slice step cannot be zero"); + return NULL; + } + } + if (slice->start == Py_None) { + if (step < 0) { + PyErr_SetString(PyExc_ValueError, + "slice start is required " + "for step < 0"); + return NULL; + } + start = 0; + } + else { + start = PyNumber_AsSsize_t(slice->start, + PyExc_ValueError); + if (start == -1 && PyErr_Occurred()) + return NULL; + } + if (slice->stop == Py_None) { + PyErr_SetString(PyExc_ValueError, + "slice stop is required"); + return NULL; + } + stop = PyNumber_AsSsize_t(slice->stop, + PyExc_ValueError); + if (stop == -1 && PyErr_Occurred()) + return NULL; + if ((step > 0 && start > stop) || + (step < 0 && start < stop)) + len = 0; + else if (step > 0) + len = (stop - start - 1) / step + 1; + else + len = (stop - start + 1) / step + 1; + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for pointer instances */ + proto = stgdict->proto; + assert(proto); + itemdict = PyType_stgdict(proto); + assert(itemdict); + if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + char *ptr = *(char **)self->b_ptr; + char *dest; + + if (len <= 0) + return PyBytes_FromStringAndSize("", 0); + if (step == 1) { + return PyBytes_FromStringAndSize(ptr + start, + len); + } + dest = (char *)PyMem_Malloc(len); + if (dest == NULL) + return PyErr_NoMemory(); + for (cur = start, i = 0; i < len; cur += step, i++) { + dest[i] = ptr[cur]; + } + np = PyBytes_FromStringAndSize(dest, len); + PyMem_Free(dest); + return np; + } #ifdef CTYPES_UNICODE - if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - wchar_t *ptr = *(wchar_t **)self->b_ptr; - wchar_t *dest; - - if (len <= 0) - return PyUnicode_FromUnicode(NULL, 0); - if (step == 1) { - return PyUnicode_FromWideChar(ptr + start, - len); - } - dest = (wchar_t *)PyMem_Malloc(len * sizeof(wchar_t)); - if (dest == NULL) - return PyErr_NoMemory(); - for (cur = start, i = 0; i < len; cur += step, i++) { - dest[i] = ptr[cur]; - } - np = PyUnicode_FromWideChar(dest, len); - PyMem_Free(dest); - return np; - } + if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + wchar_t *ptr = *(wchar_t **)self->b_ptr; + wchar_t *dest; + + if (len <= 0) + return PyUnicode_FromUnicode(NULL, 0); + if (step == 1) { + return PyUnicode_FromWideChar(ptr + start, + len); + } + dest = (wchar_t *)PyMem_Malloc(len * sizeof(wchar_t)); + if (dest == NULL) + return PyErr_NoMemory(); + for (cur = start, i = 0; i < len; cur += step, i++) { + dest[i] = ptr[cur]; + } + np = PyUnicode_FromWideChar(dest, len); + PyMem_Free(dest); + return np; + } #endif - np = PyList_New(len); - if (np == NULL) - return NULL; - - for (cur = start, i = 0; i < len; cur += step, i++) { - PyObject *v = Pointer_item(_self, cur); - PyList_SET_ITEM(np, i, v); - } - return np; - } - else { - PyErr_SetString(PyExc_TypeError, - "Pointer indices must be integer"); - return NULL; - } + np = PyList_New(len); + if (np == NULL) + return NULL; + + for (cur = start, i = 0; i < len; cur += step, i++) { + PyObject *v = Pointer_item(_self, cur); + PyList_SET_ITEM(np, i, v); + } + return np; + } + else { + PyErr_SetString(PyExc_TypeError, + "Pointer indices must be integer"); + return NULL; + } } static PySequenceMethods Pointer_as_sequence = { - 0, /* inquiry sq_length; */ - 0, /* binaryfunc sq_concat; */ - 0, /* intargfunc sq_repeat; */ - Pointer_item, /* intargfunc sq_item; */ - 0, /* intintargfunc sq_slice; */ - Pointer_ass_item, /* intobjargproc sq_ass_item; */ - 0, /* intintobjargproc sq_ass_slice; */ - 0, /* objobjproc sq_contains; */ - /* Added in release 2.0 */ - 0, /* binaryfunc sq_inplace_concat; */ - 0, /* intargfunc sq_inplace_repeat; */ + 0, /* inquiry sq_length; */ + 0, /* binaryfunc sq_concat; */ + 0, /* intargfunc sq_repeat; */ + Pointer_item, /* intargfunc sq_item; */ + 0, /* intintargfunc sq_slice; */ + Pointer_ass_item, /* intobjargproc sq_ass_item; */ + 0, /* intintobjargproc sq_ass_slice; */ + 0, /* objobjproc sq_contains; */ + /* Added in release 2.0 */ + 0, /* binaryfunc sq_inplace_concat; */ + 0, /* intargfunc sq_inplace_repeat; */ }; static PyMappingMethods Pointer_as_mapping = { - 0, - Pointer_subscript, + 0, + Pointer_subscript, }; static int Pointer_bool(CDataObject *self) { - return (*(void **)self->b_ptr != NULL); + return (*(void **)self->b_ptr != NULL); } static PyNumberMethods Pointer_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)Pointer_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)Pointer_bool, /* nb_bool */ }; PyTypeObject PyCPointer_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes._Pointer", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - &Pointer_as_number, /* tp_as_number */ - &Pointer_as_sequence, /* tp_as_sequence */ - &Pointer_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - Pointer_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)Pointer_init, /* tp_init */ - 0, /* tp_alloc */ - Pointer_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes._Pointer", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + &Pointer_as_number, /* tp_as_number */ + &Pointer_as_sequence, /* tp_as_sequence */ + &Pointer_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + Pointer_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Pointer_init, /* tp_init */ + 0, /* tp_alloc */ + Pointer_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* * Module initialization. @@ -5056,27 +5056,27 @@ comerror_init(PyObject *self, PyObject *args, PyObject *kwds) int status; if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) - return -1; + return -1; if (!PyArg_ParseTuple(args, "OOO:COMError", &hresult, &text, &details)) - return -1; + return -1; a = PySequence_GetSlice(args, 1, PySequence_Size(args)); if (!a) - return -1; + return -1; status = PyObject_SetAttrString(self, "args", a); Py_DECREF(a); if (status < 0) - return -1; + return -1; if (PyObject_SetAttrString(self, "hresult", hresult) < 0) - return -1; + return -1; if (PyObject_SetAttrString(self, "text", text) < 0) - return -1; + return -1; if (PyObject_SetAttrString(self, "details", details) < 0) - return -1; + return -1; bself = (PyBaseExceptionObject *)self; Py_DECREF(bself->args); @@ -5131,11 +5131,11 @@ static PyTypeObject PyComError_Type = { static int create_comerror(void) { - PyComError_Type.tp_base = (PyTypeObject*)PyExc_Exception; - if (PyType_Ready(&PyComError_Type) < 0) - return -1; - ComError = (PyObject*)&PyComError_Type; - return 0; + PyComError_Type.tp_base = (PyTypeObject*)PyExc_Exception; + if (PyType_Ready(&PyComError_Type) < 0) + return -1; + ComError = (PyObject*)&PyComError_Type; + return 0; } #endif @@ -5143,259 +5143,259 @@ create_comerror(void) static PyObject * string_at(const char *ptr, int size) { - if (size == -1) - return PyBytes_FromStringAndSize(ptr, strlen(ptr)); - return PyBytes_FromStringAndSize(ptr, size); + if (size == -1) + return PyBytes_FromStringAndSize(ptr, strlen(ptr)); + return PyBytes_FromStringAndSize(ptr, size); } static int cast_check_pointertype(PyObject *arg) { - StgDictObject *dict; - - if (PyCPointerTypeObject_Check(arg)) - return 1; - if (PyCFuncPtrTypeObject_Check(arg)) - return 1; - dict = PyType_stgdict(arg); - if (dict) { - if (PyUnicode_Check(dict->proto) - && (strchr("sPzUZXO", _PyUnicode_AsString(dict->proto)[0]))) { - /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ - return 1; - } - } - PyErr_Format(PyExc_TypeError, - "cast() argument 2 must be a pointer type, not %s", - PyType_Check(arg) - ? ((PyTypeObject *)arg)->tp_name - : Py_TYPE(arg)->tp_name); - return 0; + StgDictObject *dict; + + if (PyCPointerTypeObject_Check(arg)) + return 1; + if (PyCFuncPtrTypeObject_Check(arg)) + return 1; + dict = PyType_stgdict(arg); + if (dict) { + if (PyUnicode_Check(dict->proto) + && (strchr("sPzUZXO", _PyUnicode_AsString(dict->proto)[0]))) { + /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ + return 1; + } + } + PyErr_Format(PyExc_TypeError, + "cast() argument 2 must be a pointer type, not %s", + PyType_Check(arg) + ? ((PyTypeObject *)arg)->tp_name + : Py_TYPE(arg)->tp_name); + return 0; } static PyObject * cast(void *ptr, PyObject *src, PyObject *ctype) { - CDataObject *result; - if (0 == cast_check_pointertype(ctype)) - return NULL; - result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL); - if (result == NULL) - return NULL; - - /* - The casted objects '_objects' member: - - It must certainly contain the source objects one. - It must contain the source object itself. - */ - if (CDataObject_Check(src)) { - CDataObject *obj = (CDataObject *)src; - /* PyCData_GetContainer will initialize src.b_objects, we need - this so it can be shared */ - PyCData_GetContainer(obj); - /* But we need a dictionary! */ - if (obj->b_objects == Py_None) { - Py_DECREF(Py_None); - obj->b_objects = PyDict_New(); - if (obj->b_objects == NULL) - goto failed; - } - Py_XINCREF(obj->b_objects); - result->b_objects = obj->b_objects; - if (result->b_objects && PyDict_CheckExact(result->b_objects)) { - PyObject *index; - int rc; - index = PyLong_FromVoidPtr((void *)src); - if (index == NULL) - goto failed; - rc = PyDict_SetItem(result->b_objects, index, src); - Py_DECREF(index); - if (rc == -1) - goto failed; - } - } - /* Should we assert that result is a pointer type? */ - memcpy(result->b_ptr, &ptr, sizeof(void *)); - return (PyObject *)result; + CDataObject *result; + if (0 == cast_check_pointertype(ctype)) + return NULL; + result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL); + if (result == NULL) + return NULL; + + /* + The casted objects '_objects' member: + + It must certainly contain the source objects one. + It must contain the source object itself. + */ + if (CDataObject_Check(src)) { + CDataObject *obj = (CDataObject *)src; + /* PyCData_GetContainer will initialize src.b_objects, we need + this so it can be shared */ + PyCData_GetContainer(obj); + /* But we need a dictionary! */ + if (obj->b_objects == Py_None) { + Py_DECREF(Py_None); + obj->b_objects = PyDict_New(); + if (obj->b_objects == NULL) + goto failed; + } + Py_XINCREF(obj->b_objects); + result->b_objects = obj->b_objects; + if (result->b_objects && PyDict_CheckExact(result->b_objects)) { + PyObject *index; + int rc; + index = PyLong_FromVoidPtr((void *)src); + if (index == NULL) + goto failed; + rc = PyDict_SetItem(result->b_objects, index, src); + Py_DECREF(index); + if (rc == -1) + goto failed; + } + } + /* Should we assert that result is a pointer type? */ + memcpy(result->b_ptr, &ptr, sizeof(void *)); + return (PyObject *)result; failed: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } #ifdef CTYPES_UNICODE static PyObject * wstring_at(const wchar_t *ptr, int size) { - Py_ssize_t ssize = size; - if (ssize == -1) - ssize = wcslen(ptr); - return PyUnicode_FromWideChar(ptr, ssize); + Py_ssize_t ssize = size; + if (ssize == -1) + ssize = wcslen(ptr); + return PyUnicode_FromWideChar(ptr, ssize); } #endif static struct PyModuleDef _ctypesmodule = { - PyModuleDef_HEAD_INIT, - "_ctypes", - module_docs, - -1, - _ctypes_module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_ctypes", + module_docs, + -1, + _ctypes_module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__ctypes(void) { - PyObject *m; + PyObject *m; /* Note: ob_type is the metatype (the 'type'), defaults to PyType_Type, tp_base is the base type, defaults to 'object' aka PyBaseObject_Type. */ #ifdef WITH_THREAD - PyEval_InitThreads(); + PyEval_InitThreads(); #endif - m = PyModule_Create(&_ctypesmodule); - if (!m) - return NULL; - - _ctypes_ptrtype_cache = PyDict_New(); - if (_ctypes_ptrtype_cache == NULL) - return NULL; - - PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_ctypes_ptrtype_cache); - - _unpickle = PyObject_GetAttrString(m, "_unpickle"); - if (_unpickle == NULL) - return NULL; - - if (PyType_Ready(&PyCArg_Type) < 0) - return NULL; - - if (PyType_Ready(&PyCThunk_Type) < 0) - return NULL; - - /* StgDict is derived from PyDict_Type */ - PyCStgDict_Type.tp_base = &PyDict_Type; - if (PyType_Ready(&PyCStgDict_Type) < 0) - return NULL; - - /************************************************* - * - * Metaclasses - */ - - PyCStructType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCStructType_Type) < 0) - return NULL; - - UnionType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&UnionType_Type) < 0) - return NULL; - - PyCPointerType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCPointerType_Type) < 0) - return NULL; - - PyCArrayType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCArrayType_Type) < 0) - return NULL; - - PyCSimpleType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCSimpleType_Type) < 0) - return NULL; - - PyCFuncPtrType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCFuncPtrType_Type) < 0) - return NULL; - - /************************************************* - * - * Classes using a custom metaclass - */ - - if (PyType_Ready(&PyCData_Type) < 0) - return NULL; - - Py_TYPE(&Struct_Type) = &PyCStructType_Type; - Struct_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&Struct_Type) < 0) - return NULL; - PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type); - - Py_TYPE(&Union_Type) = &UnionType_Type; - Union_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&Union_Type) < 0) - return NULL; - PyModule_AddObject(m, "Union", (PyObject *)&Union_Type); - - Py_TYPE(&PyCPointer_Type) = &PyCPointerType_Type; - PyCPointer_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&PyCPointer_Type) < 0) - return NULL; - PyModule_AddObject(m, "_Pointer", (PyObject *)&PyCPointer_Type); - - Py_TYPE(&PyCArray_Type) = &PyCArrayType_Type; - PyCArray_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&PyCArray_Type) < 0) - return NULL; - PyModule_AddObject(m, "Array", (PyObject *)&PyCArray_Type); - - Py_TYPE(&Simple_Type) = &PyCSimpleType_Type; - Simple_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&Simple_Type) < 0) - return NULL; - PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type); - - Py_TYPE(&PyCFuncPtr_Type) = &PyCFuncPtrType_Type; - PyCFuncPtr_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&PyCFuncPtr_Type) < 0) - return NULL; - PyModule_AddObject(m, "CFuncPtr", (PyObject *)&PyCFuncPtr_Type); - - /************************************************* - * - * Simple classes - */ - - /* PyCField_Type is derived from PyBaseObject_Type */ - if (PyType_Ready(&PyCField_Type) < 0) - return NULL; - - /************************************************* - * - * Other stuff - */ - - DictRemover_Type.tp_new = PyType_GenericNew; - if (PyType_Ready(&DictRemover_Type) < 0) - return NULL; + m = PyModule_Create(&_ctypesmodule); + if (!m) + return NULL; + + _ctypes_ptrtype_cache = PyDict_New(); + if (_ctypes_ptrtype_cache == NULL) + return NULL; + + PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_ctypes_ptrtype_cache); + + _unpickle = PyObject_GetAttrString(m, "_unpickle"); + if (_unpickle == NULL) + return NULL; + + if (PyType_Ready(&PyCArg_Type) < 0) + return NULL; + + if (PyType_Ready(&PyCThunk_Type) < 0) + return NULL; + + /* StgDict is derived from PyDict_Type */ + PyCStgDict_Type.tp_base = &PyDict_Type; + if (PyType_Ready(&PyCStgDict_Type) < 0) + return NULL; + + /************************************************* + * + * Metaclasses + */ + + PyCStructType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCStructType_Type) < 0) + return NULL; + + UnionType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&UnionType_Type) < 0) + return NULL; + + PyCPointerType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCPointerType_Type) < 0) + return NULL; + + PyCArrayType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCArrayType_Type) < 0) + return NULL; + + PyCSimpleType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCSimpleType_Type) < 0) + return NULL; + + PyCFuncPtrType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCFuncPtrType_Type) < 0) + return NULL; + + /************************************************* + * + * Classes using a custom metaclass + */ + + if (PyType_Ready(&PyCData_Type) < 0) + return NULL; + + Py_TYPE(&Struct_Type) = &PyCStructType_Type; + Struct_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&Struct_Type) < 0) + return NULL; + PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type); + + Py_TYPE(&Union_Type) = &UnionType_Type; + Union_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&Union_Type) < 0) + return NULL; + PyModule_AddObject(m, "Union", (PyObject *)&Union_Type); + + Py_TYPE(&PyCPointer_Type) = &PyCPointerType_Type; + PyCPointer_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&PyCPointer_Type) < 0) + return NULL; + PyModule_AddObject(m, "_Pointer", (PyObject *)&PyCPointer_Type); + + Py_TYPE(&PyCArray_Type) = &PyCArrayType_Type; + PyCArray_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&PyCArray_Type) < 0) + return NULL; + PyModule_AddObject(m, "Array", (PyObject *)&PyCArray_Type); + + Py_TYPE(&Simple_Type) = &PyCSimpleType_Type; + Simple_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&Simple_Type) < 0) + return NULL; + PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type); + + Py_TYPE(&PyCFuncPtr_Type) = &PyCFuncPtrType_Type; + PyCFuncPtr_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&PyCFuncPtr_Type) < 0) + return NULL; + PyModule_AddObject(m, "CFuncPtr", (PyObject *)&PyCFuncPtr_Type); + + /************************************************* + * + * Simple classes + */ + + /* PyCField_Type is derived from PyBaseObject_Type */ + if (PyType_Ready(&PyCField_Type) < 0) + return NULL; + + /************************************************* + * + * Other stuff + */ + + DictRemover_Type.tp_new = PyType_GenericNew; + if (PyType_Ready(&DictRemover_Type) < 0) + return NULL; #ifdef MS_WIN32 - if (create_comerror() < 0) - return NULL; - PyModule_AddObject(m, "COMError", ComError); + if (create_comerror() < 0) + return NULL; + PyModule_AddObject(m, "COMError", ComError); - PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyLong_FromLong(FUNCFLAG_HRESULT)); - PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyLong_FromLong(FUNCFLAG_STDCALL)); + PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyLong_FromLong(FUNCFLAG_HRESULT)); + PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyLong_FromLong(FUNCFLAG_STDCALL)); #endif - PyModule_AddObject(m, "FUNCFLAG_CDECL", PyLong_FromLong(FUNCFLAG_CDECL)); - PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyLong_FromLong(FUNCFLAG_USE_ERRNO)); - PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyLong_FromLong(FUNCFLAG_USE_LASTERROR)); - PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyLong_FromLong(FUNCFLAG_PYTHONAPI)); - PyModule_AddStringConstant(m, "__version__", "1.1.0"); - - PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove)); - PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset)); - PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at)); - PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast)); + PyModule_AddObject(m, "FUNCFLAG_CDECL", PyLong_FromLong(FUNCFLAG_CDECL)); + PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyLong_FromLong(FUNCFLAG_USE_ERRNO)); + PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyLong_FromLong(FUNCFLAG_USE_LASTERROR)); + PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyLong_FromLong(FUNCFLAG_PYTHONAPI)); + PyModule_AddStringConstant(m, "__version__", "1.1.0"); + + PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove)); + PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset)); + PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at)); + PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast)); #ifdef CTYPES_UNICODE - PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at)); + PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at)); #endif /* If RTLD_LOCAL is not defined (Windows!), set it to zero. */ @@ -5410,15 +5410,15 @@ PyInit__ctypes(void) #define RTLD_GLOBAL RTLD_LOCAL #endif - PyModule_AddObject(m, "RTLD_LOCAL", PyLong_FromLong(RTLD_LOCAL)); - PyModule_AddObject(m, "RTLD_GLOBAL", PyLong_FromLong(RTLD_GLOBAL)); - - PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL); - if (PyExc_ArgError) { - Py_INCREF(PyExc_ArgError); - PyModule_AddObject(m, "ArgumentError", PyExc_ArgError); - } - return m; + PyModule_AddObject(m, "RTLD_LOCAL", PyLong_FromLong(RTLD_LOCAL)); + PyModule_AddObject(m, "RTLD_GLOBAL", PyLong_FromLong(RTLD_GLOBAL)); + + PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL); + if (PyExc_ArgError) { + Py_INCREF(PyExc_ArgError); + PyModule_AddObject(m, "ArgumentError", PyExc_ArgError); + } + return m; } /* diff --git a/Modules/_ctypes/_ctypes_test.c b/Modules/_ctypes/_ctypes_test.c index 2d957de..36bd0a1 100644 --- a/Modules/_ctypes/_ctypes_test.c +++ b/Modules/_ctypes/_ctypes_test.c @@ -14,152 +14,152 @@ EXPORT(void)testfunc_array(int values[4]) { - printf("testfunc_array %d %d %d %d\n", - values[0], - values[1], - values[2], - values[3]); + printf("testfunc_array %d %d %d %d\n", + values[0], + values[1], + values[2], + values[3]); } EXPORT(long double)testfunc_Ddd(double a, double b) { - long double result = (long double)(a * b); - printf("testfunc_Ddd(%p, %p)\n", &a, &b); - printf("testfunc_Ddd(%g, %g)\n", a, b); - return result; + long double result = (long double)(a * b); + printf("testfunc_Ddd(%p, %p)\n", &a, &b); + printf("testfunc_Ddd(%g, %g)\n", a, b); + return result; } EXPORT(long double)testfunc_DDD(long double a, long double b) { - long double result = a * b; - printf("testfunc_DDD(%p, %p)\n", &a, &b); - printf("testfunc_DDD(%Lg, %Lg)\n", a, b); - return result; + long double result = a * b; + printf("testfunc_DDD(%p, %p)\n", &a, &b); + printf("testfunc_DDD(%Lg, %Lg)\n", a, b); + return result; } EXPORT(int)testfunc_iii(int a, int b) { - int result = a * b; - printf("testfunc_iii(%p, %p)\n", &a, &b); - return result; + int result = a * b; + printf("testfunc_iii(%p, %p)\n", &a, &b); + return result; } EXPORT(int)myprintf(char *fmt, ...) { - int result; - va_list argptr; - va_start(argptr, fmt); - result = vprintf(fmt, argptr); - va_end(argptr); - return result; + int result; + va_list argptr; + va_start(argptr, fmt); + result = vprintf(fmt, argptr); + va_end(argptr); + return result; } EXPORT(char *)my_strtok(char *token, const char *delim) { - return strtok(token, delim); + return strtok(token, delim); } EXPORT(char *)my_strchr(const char *s, int c) { - return strchr(s, c); + return strchr(s, c); } EXPORT(double) my_sqrt(double a) { - return sqrt(a); + return sqrt(a); } EXPORT(void) my_qsort(void *base, size_t num, size_t width, int(*compare)(const void*, const void*)) { - qsort(base, num, width, compare); + qsort(base, num, width, compare); } EXPORT(int *) _testfunc_ai8(int a[8]) { - return a; + return a; } EXPORT(void) _testfunc_v(int a, int b, int *presult) { - *presult = a + b; + *presult = a + b; } EXPORT(int) _testfunc_i_bhilfd(signed char b, short h, int i, long l, float f, double d) { -/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (int)(b + h + i + l + f + d); + return (int)(b + h + i + l + f + d); } EXPORT(float) _testfunc_f_bhilfd(signed char b, short h, int i, long l, float f, double d) { -/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (float)(b + h + i + l + f + d); + return (float)(b + h + i + l + f + d); } EXPORT(double) _testfunc_d_bhilfd(signed char b, short h, int i, long l, float f, double d) { -/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (double)(b + h + i + l + f + d); + return (double)(b + h + i + l + f + d); } EXPORT(long double) _testfunc_D_bhilfD(signed char b, short h, int i, long l, float f, long double d) { -/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (long double)(b + h + i + l + f + d); + return (long double)(b + h + i + l + f + d); } EXPORT(char *) _testfunc_p_p(void *s) { - return (char *)s; + return (char *)s; } EXPORT(void *) _testfunc_c_p_p(int *argcp, char **argv) { - return argv[(*argcp)-1]; + return argv[(*argcp)-1]; } EXPORT(void *) get_strchr(void) { - return (void *)strchr; + return (void *)strchr; } EXPORT(char *) my_strdup(char *src) { - char *dst = (char *)malloc(strlen(src)+1); - if (!dst) - return NULL; - strcpy(dst, src); - return dst; + char *dst = (char *)malloc(strlen(src)+1); + if (!dst) + return NULL; + strcpy(dst, src); + return dst; } EXPORT(void)my_free(void *ptr) { - free(ptr); + free(ptr); } #ifdef HAVE_WCHAR_H EXPORT(wchar_t *) my_wcsdup(wchar_t *src) { - size_t len = wcslen(src); - wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t)); - if (ptr == NULL) - return NULL; - memcpy(ptr, src, (len+1) * sizeof(wchar_t)); - return ptr; + size_t len = wcslen(src); + wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t)); + if (ptr == NULL) + return NULL; + memcpy(ptr, src, (len+1) * sizeof(wchar_t)); + return ptr; } EXPORT(size_t) my_wcslen(wchar_t *src) { - return wcslen(src); + return wcslen(src); } #endif @@ -170,158 +170,158 @@ EXPORT(size_t) my_wcslen(wchar_t *src) #endif typedef struct { - int (*c)(int, int); - int (__stdcall *s)(int, int); + int (*c)(int, int); + int (__stdcall *s)(int, int); } FUNCS; EXPORT(int) _testfunc_callfuncp(FUNCS *fp) { - fp->c(1, 2); - fp->s(3, 4); - return 0; + fp->c(1, 2); + fp->s(3, 4); + return 0; } EXPORT(int) _testfunc_deref_pointer(int *pi) { - return *pi; + return *pi; } #ifdef MS_WIN32 EXPORT(int) _testfunc_piunk(IUnknown FAR *piunk) { - piunk->lpVtbl->AddRef(piunk); - return piunk->lpVtbl->Release(piunk); + piunk->lpVtbl->AddRef(piunk); + return piunk->lpVtbl->Release(piunk); } #endif EXPORT(int) _testfunc_callback_with_pointer(int (*func)(int *)) { - int table[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + int table[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - return (*func)(table); + return (*func)(table); } #ifdef HAVE_LONG_LONG EXPORT(PY_LONG_LONG) _testfunc_q_bhilfdq(signed char b, short h, int i, long l, float f, - double d, PY_LONG_LONG q) + double d, PY_LONG_LONG q) { - return (PY_LONG_LONG)(b + h + i + l + f + d + q); + return (PY_LONG_LONG)(b + h + i + l + f + d + q); } EXPORT(PY_LONG_LONG) _testfunc_q_bhilfd(signed char b, short h, int i, long l, float f, double d) { - return (PY_LONG_LONG)(b + h + i + l + f + d); + return (PY_LONG_LONG)(b + h + i + l + f + d); } EXPORT(int) _testfunc_callback_i_if(int value, int (*func)(int)) { - int sum = 0; - while (value != 0) { - sum += func(value); - value /= 2; - } - return sum; + int sum = 0; + while (value != 0) { + sum += func(value); + value /= 2; + } + return sum; } EXPORT(PY_LONG_LONG) _testfunc_callback_q_qf(PY_LONG_LONG value, - PY_LONG_LONG (*func)(PY_LONG_LONG)) + PY_LONG_LONG (*func)(PY_LONG_LONG)) { - PY_LONG_LONG sum = 0; + PY_LONG_LONG sum = 0; - while (value != 0) { - sum += func(value); - value /= 2; - } - return sum; + while (value != 0) { + sum += func(value); + value /= 2; + } + return sum; } #endif typedef struct { - char *name; - char *value; + char *name; + char *value; } SPAM; typedef struct { - char *name; - int num_spams; - SPAM *spams; + char *name; + int num_spams; + SPAM *spams; } EGG; SPAM my_spams[2] = { - { "name1", "value1" }, - { "name2", "value2" }, + { "name1", "value1" }, + { "name2", "value2" }, }; EGG my_eggs[1] = { - { "first egg", 1, my_spams } + { "first egg", 1, my_spams } }; EXPORT(int) getSPAMANDEGGS(EGG **eggs) { - *eggs = my_eggs; - return 1; + *eggs = my_eggs; + return 1; } typedef struct tagpoint { - int x; - int y; + int x; + int y; } point; EXPORT(int) _testfunc_byval(point in, point *pout) { - if (pout) { - pout->x = in.x; - pout->y = in.y; - } - return in.x + in.y; + if (pout) { + pout->x = in.x; + pout->y = in.y; + } + return in.x + in.y; } EXPORT (int) an_integer = 42; EXPORT(int) get_an_integer(void) { - return an_integer; + return an_integer; } EXPORT(double) integrate(double a, double b, double (*f)(double), long nstep) { - double x, sum=0.0, dx=(b-a)/(double)nstep; - for(x=a+0.5*dx; (b-x)*(x-a)>0.0; x+=dx) - sum += f(x); - return sum/(double)nstep; + double x, sum=0.0, dx=(b-a)/(double)nstep; + for(x=a+0.5*dx; (b-x)*(x-a)>0.0; x+=dx) + sum += f(x); + return sum/(double)nstep; } typedef struct { - void (*initialize)(void *(*)(int), void(*)(void *)); + void (*initialize)(void *(*)(int), void(*)(void *)); } xxx_library; static void _xxx_init(void *(*Xalloc)(int), void (*Xfree)(void *)) { - void *ptr; - - printf("_xxx_init got %p %p\n", Xalloc, Xfree); - printf("calling\n"); - ptr = Xalloc(32); - Xfree(ptr); - printf("calls done, ptr was %p\n", ptr); + void *ptr; + + printf("_xxx_init got %p %p\n", Xalloc, Xfree); + printf("calling\n"); + ptr = Xalloc(32); + Xfree(ptr); + printf("calls done, ptr was %p\n", ptr); } xxx_library _xxx_lib = { - _xxx_init + _xxx_init }; EXPORT(xxx_library) *library_get(void) { - return &_xxx_lib; + return &_xxx_lib; } #ifdef MS_WIN32 /* See Don Box (german), pp 79ff. */ EXPORT(void) GetString(BSTR *pbstr) { - *pbstr = SysAllocString(L"Goodbye!"); + *pbstr = SysAllocString(L"Goodbye!"); } #endif @@ -330,12 +330,12 @@ EXPORT(void) GetString(BSTR *pbstr) */ PyObject *py_func_si(PyObject *self, PyObject *args) { - char *name; - int i; - if (!PyArg_ParseTuple(args, "si", &name, &i)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + char *name; + int i; + if (!PyArg_ParseTuple(args, "si", &name, &i)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } EXPORT(void) _py_func_si(char *s, int i) @@ -344,8 +344,8 @@ EXPORT(void) _py_func_si(char *s, int i) PyObject *py_func(PyObject *self, PyObject *args) { - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } EXPORT(void) _py_func(void) @@ -356,64 +356,64 @@ EXPORT(PY_LONG_LONG) last_tf_arg_s; EXPORT(unsigned PY_LONG_LONG) last_tf_arg_u; struct BITS { - int A: 1, B:2, C:3, D:4, E: 5, F: 6, G: 7, H: 8, I: 9; - short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7; + int A: 1, B:2, C:3, D:4, E: 5, F: 6, G: 7, H: 8, I: 9; + short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7; }; EXPORT(void) set_bitfields(struct BITS *bits, char name, int value) { - switch (name) { - case 'A': bits->A = value; break; - case 'B': bits->B = value; break; - case 'C': bits->C = value; break; - case 'D': bits->D = value; break; - case 'E': bits->E = value; break; - case 'F': bits->F = value; break; - case 'G': bits->G = value; break; - case 'H': bits->H = value; break; - case 'I': bits->I = value; break; - - case 'M': bits->M = value; break; - case 'N': bits->N = value; break; - case 'O': bits->O = value; break; - case 'P': bits->P = value; break; - case 'Q': bits->Q = value; break; - case 'R': bits->R = value; break; - case 'S': bits->S = value; break; - } + switch (name) { + case 'A': bits->A = value; break; + case 'B': bits->B = value; break; + case 'C': bits->C = value; break; + case 'D': bits->D = value; break; + case 'E': bits->E = value; break; + case 'F': bits->F = value; break; + case 'G': bits->G = value; break; + case 'H': bits->H = value; break; + case 'I': bits->I = value; break; + + case 'M': bits->M = value; break; + case 'N': bits->N = value; break; + case 'O': bits->O = value; break; + case 'P': bits->P = value; break; + case 'Q': bits->Q = value; break; + case 'R': bits->R = value; break; + case 'S': bits->S = value; break; + } } EXPORT(int) unpack_bitfields(struct BITS *bits, char name) { - switch (name) { - case 'A': return bits->A; - case 'B': return bits->B; - case 'C': return bits->C; - case 'D': return bits->D; - case 'E': return bits->E; - case 'F': return bits->F; - case 'G': return bits->G; - case 'H': return bits->H; - case 'I': return bits->I; - - case 'M': return bits->M; - case 'N': return bits->N; - case 'O': return bits->O; - case 'P': return bits->P; - case 'Q': return bits->Q; - case 'R': return bits->R; - case 'S': return bits->S; - } - return 0; + switch (name) { + case 'A': return bits->A; + case 'B': return bits->B; + case 'C': return bits->C; + case 'D': return bits->D; + case 'E': return bits->E; + case 'F': return bits->F; + case 'G': return bits->G; + case 'H': return bits->H; + case 'I': return bits->I; + + case 'M': return bits->M; + case 'N': return bits->N; + case 'O': return bits->O; + case 'P': return bits->P; + case 'Q': return bits->Q; + case 'R': return bits->R; + case 'S': return bits->S; + } + return 0; } static PyMethodDef module_methods[] = { -/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, - {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, +/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, + {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, */ - {"func_si", py_func_si, METH_VARARGS}, - {"func", py_func, METH_NOARGS}, - { NULL, NULL, 0, NULL}, + {"func_si", py_func_si, METH_VARARGS}, + {"func", py_func, METH_NOARGS}, + { NULL, NULL, 0, NULL}, }; #define S last_tf_arg_s = (PY_LONG_LONG)c @@ -483,80 +483,80 @@ EXPORT(void) __stdcall s_tv_i(int c) { S; return; } #endif /********/ - + #ifndef MS_WIN32 typedef struct { - long x; - long y; + long x; + long y; } POINT; typedef struct { - long left; - long top; - long right; - long bottom; + long left; + long top; + long right; + long bottom; } RECT; #endif EXPORT(int) PointInRect(RECT *prc, POINT pt) { - if (pt.x < prc->left) - return 0; - if (pt.x > prc->right) - return 0; - if (pt.y < prc->top) - return 0; - if (pt.y > prc->bottom) - return 0; - return 1; + if (pt.x < prc->left) + return 0; + if (pt.x > prc->right) + return 0; + if (pt.y < prc->top) + return 0; + if (pt.y > prc->bottom) + return 0; + return 1; } typedef struct { - short x; - short y; + short x; + short y; } S2H; EXPORT(S2H) ret_2h_func(S2H inp) { - inp.x *= 2; - inp.y *= 3; - return inp; + inp.x *= 2; + inp.y *= 3; + return inp; } typedef struct { - int a, b, c, d, e, f, g, h; + int a, b, c, d, e, f, g, h; } S8I; EXPORT(S8I) ret_8i_func(S8I inp) { - inp.a *= 2; - inp.b *= 3; - inp.c *= 4; - inp.d *= 5; - inp.e *= 6; - inp.f *= 7; - inp.g *= 8; - inp.h *= 9; - return inp; + inp.a *= 2; + inp.b *= 3; + inp.c *= 4; + inp.d *= 5; + inp.e *= 6; + inp.f *= 7; + inp.g *= 8; + inp.h *= 9; + return inp; } EXPORT(int) GetRectangle(int flag, RECT *prect) { - if (flag == 0) - return 0; - prect->left = (int)flag; - prect->top = (int)flag + 1; - prect->right = (int)flag + 2; - prect->bottom = (int)flag + 3; - return 1; + if (flag == 0) + return 0; + prect->left = (int)flag; + prect->top = (int)flag + 1; + prect->right = (int)flag + 2; + prect->bottom = (int)flag + 3; + return 1; } EXPORT(void) TwoOutArgs(int a, int *pi, int b, int *pj) { - *pi += a; - *pj += b; + *pi += a; + *pj += b; } #ifdef MS_WIN32 @@ -571,32 +571,32 @@ EXPORT(S8I) __stdcall s_ret_8i_func(S8I inp) { return ret_8i_func(inp); } EXPORT (HRESULT) KeepObject(IUnknown *punk) { - static IUnknown *pobj; - if (punk) - punk->lpVtbl->AddRef(punk); - if (pobj) - pobj->lpVtbl->Release(pobj); - pobj = punk; - return S_OK; + static IUnknown *pobj; + if (punk) + punk->lpVtbl->AddRef(punk); + if (pobj) + pobj->lpVtbl->Release(pobj); + pobj = punk; + return S_OK; } #endif static struct PyModuleDef _ctypes_testmodule = { - PyModuleDef_HEAD_INIT, - "_ctypes_test", - NULL, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_ctypes_test", + NULL, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__ctypes_test(void) { - return PyModule_Create(&_ctypes_testmodule); + return PyModule_Create(&_ctypes_testmodule); } diff --git a/Modules/_ctypes/callbacks.c b/Modules/_ctypes/callbacks.c index 9b2cd3f..5c82f77 100644 --- a/Modules/_ctypes/callbacks.c +++ b/Modules/_ctypes/callbacks.c @@ -12,65 +12,65 @@ static void CThunkObject_dealloc(PyObject *_self) { - CThunkObject *self = (CThunkObject *)_self; - Py_XDECREF(self->converters); - Py_XDECREF(self->callable); - Py_XDECREF(self->restype); - if (self->pcl) - _ctypes_free_closure(self->pcl); - PyObject_GC_Del(self); + CThunkObject *self = (CThunkObject *)_self; + Py_XDECREF(self->converters); + Py_XDECREF(self->callable); + Py_XDECREF(self->restype); + if (self->pcl) + _ctypes_free_closure(self->pcl); + PyObject_GC_Del(self); } static int CThunkObject_traverse(PyObject *_self, visitproc visit, void *arg) { - CThunkObject *self = (CThunkObject *)_self; - Py_VISIT(self->converters); - Py_VISIT(self->callable); - Py_VISIT(self->restype); - return 0; + CThunkObject *self = (CThunkObject *)_self; + Py_VISIT(self->converters); + Py_VISIT(self->callable); + Py_VISIT(self->restype); + return 0; } static int CThunkObject_clear(PyObject *_self) { - CThunkObject *self = (CThunkObject *)_self; - Py_CLEAR(self->converters); - Py_CLEAR(self->callable); - Py_CLEAR(self->restype); - return 0; + CThunkObject *self = (CThunkObject *)_self; + Py_CLEAR(self->converters); + Py_CLEAR(self->callable); + Py_CLEAR(self->restype); + return 0; } PyTypeObject PyCThunk_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.CThunkObject", - sizeof(CThunkObject), /* tp_basicsize */ - sizeof(ffi_type), /* tp_itemsize */ - CThunkObject_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "CThunkObject", /* tp_doc */ - CThunkObject_traverse, /* tp_traverse */ - CThunkObject_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.CThunkObject", + sizeof(CThunkObject), /* tp_basicsize */ + sizeof(ffi_type), /* tp_itemsize */ + CThunkObject_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "CThunkObject", /* tp_doc */ + CThunkObject_traverse, /* tp_traverse */ + CThunkObject_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ }; /**************************************************************/ @@ -78,75 +78,75 @@ PyTypeObject PyCThunk_Type = { static void PrintError(char *msg, ...) { - char buf[512]; - PyObject *f = PySys_GetObject("stderr"); - va_list marker; - - va_start(marker, msg); - vsnprintf(buf, sizeof(buf), msg, marker); - va_end(marker); - if (f != NULL && f != Py_None) - PyFile_WriteString(buf, f); - PyErr_Print(); + char buf[512]; + PyObject *f = PySys_GetObject("stderr"); + va_list marker; + + va_start(marker, msg); + vsnprintf(buf, sizeof(buf), msg, marker); + va_end(marker); + if (f != NULL && f != Py_None) + PyFile_WriteString(buf, f); + PyErr_Print(); } /* after code that pyrex generates */ void _ctypes_add_traceback(char *funcname, char *filename, int lineno) { - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - PyObject *py_globals = 0; - PyObject *empty_tuple = 0; - PyObject *empty_string = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - - py_srcfile = PyUnicode_DecodeFSDefault(filename); - if (!py_srcfile) goto bad; - py_funcname = PyUnicode_FromString(funcname); - if (!py_funcname) goto bad; - py_globals = PyDict_New(); - if (!py_globals) goto bad; - empty_tuple = PyTuple_New(0); - if (!empty_tuple) goto bad; - empty_string = PyBytes_FromString(""); - if (!empty_string) goto bad; - py_code = PyCode_New( - 0, /*int argcount,*/ - 0, /*int kwonlyargcount,*/ - 0, /*int nlocals,*/ - 0, /*int stacksize,*/ - 0, /*int flags,*/ - empty_string, /*PyObject *code,*/ - empty_tuple, /*PyObject *consts,*/ - empty_tuple, /*PyObject *names,*/ - empty_tuple, /*PyObject *varnames,*/ - empty_tuple, /*PyObject *freevars,*/ - empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - lineno, /*int firstlineno,*/ - empty_string /*PyObject *lnotab*/ - ); - if (!py_code) goto bad; - py_frame = PyFrame_New( - PyThreadState_Get(), /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - py_globals, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - py_frame->f_lineno = lineno; - PyTraceBack_Here(py_frame); + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + PyObject *py_globals = 0; + PyObject *empty_tuple = 0; + PyObject *empty_string = 0; + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + + py_srcfile = PyUnicode_DecodeFSDefault(filename); + if (!py_srcfile) goto bad; + py_funcname = PyUnicode_FromString(funcname); + if (!py_funcname) goto bad; + py_globals = PyDict_New(); + if (!py_globals) goto bad; + empty_tuple = PyTuple_New(0); + if (!empty_tuple) goto bad; + empty_string = PyBytes_FromString(""); + if (!empty_string) goto bad; + py_code = PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + empty_string, /*PyObject *code,*/ + empty_tuple, /*PyObject *consts,*/ + empty_tuple, /*PyObject *names,*/ + empty_tuple, /*PyObject *varnames,*/ + empty_tuple, /*PyObject *freevars,*/ + empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + lineno, /*int firstlineno,*/ + empty_string /*PyObject *lnotab*/ + ); + if (!py_code) goto bad; + py_frame = PyFrame_New( + PyThreadState_Get(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = lineno; + PyTraceBack_Here(py_frame); bad: - Py_XDECREF(py_globals); - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - Py_XDECREF(empty_tuple); - Py_XDECREF(empty_string); - Py_XDECREF(py_code); - Py_XDECREF(py_frame); + Py_XDECREF(py_globals); + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + Py_XDECREF(empty_tuple); + Py_XDECREF(empty_string); + Py_XDECREF(py_code); + Py_XDECREF(py_frame); } #ifdef MS_WIN32 @@ -163,15 +163,15 @@ void _ctypes_add_traceback(char *funcname, char *filename, int lineno) static void TryAddRef(StgDictObject *dict, CDataObject *obj) { - IUnknown *punk; + IUnknown *punk; - if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_")) - return; + if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_")) + return; - punk = *(IUnknown **)obj->b_ptr; - if (punk) - punk->lpVtbl->AddRef(punk); - return; + punk = *(IUnknown **)obj->b_ptr; + if (punk) + punk->lpVtbl->AddRef(punk); + return; } #endif @@ -181,421 +181,421 @@ TryAddRef(StgDictObject *dict, CDataObject *obj) * */ static void _CallPythonObject(void *mem, - ffi_type *restype, - SETFUNC setfunc, - PyObject *callable, - PyObject *converters, - int flags, - void **pArgs) + ffi_type *restype, + SETFUNC setfunc, + PyObject *callable, + PyObject *converters, + int flags, + void **pArgs) { - Py_ssize_t i; - PyObject *result; - PyObject *arglist = NULL; - Py_ssize_t nArgs; - PyObject *error_object = NULL; - int *space; + Py_ssize_t i; + PyObject *result; + PyObject *arglist = NULL; + Py_ssize_t nArgs; + PyObject *error_object = NULL; + int *space; #ifdef WITH_THREAD - PyGILState_STATE state = PyGILState_Ensure(); + PyGILState_STATE state = PyGILState_Ensure(); #endif - nArgs = PySequence_Length(converters); - /* Hm. What to return in case of error? - For COM, 0xFFFFFFFF seems better than 0. - */ - if (nArgs < 0) { - PrintError("BUG: PySequence_Length"); - goto Done; - } - - arglist = PyTuple_New(nArgs); - if (!arglist) { - PrintError("PyTuple_New()"); - goto Done; - } - for (i = 0; i < nArgs; ++i) { - /* Note: new reference! */ - PyObject *cnv = PySequence_GetItem(converters, i); - StgDictObject *dict; - if (cnv) - dict = PyType_stgdict(cnv); - else { - PrintError("Getting argument converter %d\n", i); - goto Done; - } - - if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) { - PyObject *v = dict->getfunc(*pArgs, dict->size); - if (!v) { - PrintError("create argument %d:\n", i); - Py_DECREF(cnv); - goto Done; - } - PyTuple_SET_ITEM(arglist, i, v); - /* XXX XXX XX - We have the problem that c_byte or c_short have dict->size of - 1 resp. 4, but these parameters are pushed as sizeof(int) bytes. - BTW, the same problem occurrs when they are pushed as parameters - */ - } else if (dict) { - /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */ - CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL); - if (!obj) { - PrintError("create argument %d:\n", i); - Py_DECREF(cnv); - goto Done; - } - if (!CDataObject_Check(obj)) { - Py_DECREF(obj); - Py_DECREF(cnv); - PrintError("unexpected result of create argument %d:\n", i); - goto Done; - } - memcpy(obj->b_ptr, *pArgs, dict->size); - PyTuple_SET_ITEM(arglist, i, (PyObject *)obj); + nArgs = PySequence_Length(converters); + /* Hm. What to return in case of error? + For COM, 0xFFFFFFFF seems better than 0. + */ + if (nArgs < 0) { + PrintError("BUG: PySequence_Length"); + goto Done; + } + + arglist = PyTuple_New(nArgs); + if (!arglist) { + PrintError("PyTuple_New()"); + goto Done; + } + for (i = 0; i < nArgs; ++i) { + /* Note: new reference! */ + PyObject *cnv = PySequence_GetItem(converters, i); + StgDictObject *dict; + if (cnv) + dict = PyType_stgdict(cnv); + else { + PrintError("Getting argument converter %d\n", i); + goto Done; + } + + if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) { + PyObject *v = dict->getfunc(*pArgs, dict->size); + if (!v) { + PrintError("create argument %d:\n", i); + Py_DECREF(cnv); + goto Done; + } + PyTuple_SET_ITEM(arglist, i, v); + /* XXX XXX XX + We have the problem that c_byte or c_short have dict->size of + 1 resp. 4, but these parameters are pushed as sizeof(int) bytes. + BTW, the same problem occurrs when they are pushed as parameters + */ + } else if (dict) { + /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */ + CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL); + if (!obj) { + PrintError("create argument %d:\n", i); + Py_DECREF(cnv); + goto Done; + } + if (!CDataObject_Check(obj)) { + Py_DECREF(obj); + Py_DECREF(cnv); + PrintError("unexpected result of create argument %d:\n", i); + goto Done; + } + memcpy(obj->b_ptr, *pArgs, dict->size); + PyTuple_SET_ITEM(arglist, i, (PyObject *)obj); #ifdef MS_WIN32 - TryAddRef(dict, obj); + TryAddRef(dict, obj); #endif - } else { - PyErr_SetString(PyExc_TypeError, - "cannot build parameter"); - PrintError("Parsing argument %d\n", i); - Py_DECREF(cnv); - goto Done; - } - Py_DECREF(cnv); - /* XXX error handling! */ - pArgs++; - } + } else { + PyErr_SetString(PyExc_TypeError, + "cannot build parameter"); + PrintError("Parsing argument %d\n", i); + Py_DECREF(cnv); + goto Done; + } + Py_DECREF(cnv); + /* XXX error handling! */ + pArgs++; + } #define CHECK(what, x) \ if (x == NULL) _ctypes_add_traceback(what, "_ctypes/callbacks.c", __LINE__ - 1), PyErr_Print() - if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { - error_object = _ctypes_get_errobj(&space); - if (error_object == NULL) - goto Done; - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } + if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { + error_object = _ctypes_get_errobj(&space); + if (error_object == NULL) + goto Done; + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } #ifdef MS_WIN32 - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } #endif - } + } - result = PyObject_CallObject(callable, arglist); - CHECK("'calling callback function'", result); + result = PyObject_CallObject(callable, arglist); + CHECK("'calling callback function'", result); #ifdef MS_WIN32 - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } #endif - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } - Py_XDECREF(error_object); - - if ((restype != &ffi_type_void) && result) { - PyObject *keep; - assert(setfunc); + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } + Py_XDECREF(error_object); + + if ((restype != &ffi_type_void) && result) { + PyObject *keep; + assert(setfunc); #ifdef WORDS_BIGENDIAN - /* See the corresponding code in callproc.c, around line 961 */ - if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg)) - mem = (char *)mem + sizeof(ffi_arg) - restype->size; + /* See the corresponding code in callproc.c, around line 961 */ + if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg)) + mem = (char *)mem + sizeof(ffi_arg) - restype->size; #endif - keep = setfunc(mem, result, 0); - CHECK("'converting callback result'", keep); - /* keep is an object we have to keep alive so that the result - stays valid. If there is no such object, the setfunc will - have returned Py_None. - - If there is such an object, we have no choice than to keep - it alive forever - but a refcount and/or memory leak will - be the result. EXCEPT when restype is py_object - Python - itself knows how to manage the refcount of these objects. - */ - if (keep == NULL) /* Could not convert callback result. */ - PyErr_WriteUnraisable(callable); - else if (keep == Py_None) /* Nothing to keep */ - Py_DECREF(keep); - else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) { - if (-1 == PyErr_WarnEx(PyExc_RuntimeWarning, - "memory leak in callback function.", - 1)) - PyErr_WriteUnraisable(callable); - } - } - Py_XDECREF(result); + keep = setfunc(mem, result, 0); + CHECK("'converting callback result'", keep); + /* keep is an object we have to keep alive so that the result + stays valid. If there is no such object, the setfunc will + have returned Py_None. + + If there is such an object, we have no choice than to keep + it alive forever - but a refcount and/or memory leak will + be the result. EXCEPT when restype is py_object - Python + itself knows how to manage the refcount of these objects. + */ + if (keep == NULL) /* Could not convert callback result. */ + PyErr_WriteUnraisable(callable); + else if (keep == Py_None) /* Nothing to keep */ + Py_DECREF(keep); + else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) { + if (-1 == PyErr_WarnEx(PyExc_RuntimeWarning, + "memory leak in callback function.", + 1)) + PyErr_WriteUnraisable(callable); + } + } + Py_XDECREF(result); Done: - Py_XDECREF(arglist); + Py_XDECREF(arglist); #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif } static void closure_fcn(ffi_cif *cif, - void *resp, - void **args, - void *userdata) + void *resp, + void **args, + void *userdata) { - CThunkObject *p = (CThunkObject *)userdata; - - _CallPythonObject(resp, - p->ffi_restype, - p->setfunc, - p->callable, - p->converters, - p->flags, - args); + CThunkObject *p = (CThunkObject *)userdata; + + _CallPythonObject(resp, + p->ffi_restype, + p->setfunc, + p->callable, + p->converters, + p->flags, + args); } static CThunkObject* CThunkObject_new(Py_ssize_t nArgs) { - CThunkObject *p; - int i; - - p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs); - if (p == NULL) { - PyErr_NoMemory(); - return NULL; - } - - p->pcl = NULL; - memset(&p->cif, 0, sizeof(p->cif)); - p->converters = NULL; - p->callable = NULL; - p->setfunc = NULL; - p->ffi_restype = NULL; - - for (i = 0; i < nArgs + 1; ++i) - p->atypes[i] = NULL; - PyObject_GC_Track((PyObject *)p); - return p; + CThunkObject *p; + int i; + + p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs); + if (p == NULL) { + PyErr_NoMemory(); + return NULL; + } + + p->pcl = NULL; + memset(&p->cif, 0, sizeof(p->cif)); + p->converters = NULL; + p->callable = NULL; + p->setfunc = NULL; + p->ffi_restype = NULL; + + for (i = 0; i < nArgs + 1; ++i) + p->atypes[i] = NULL; + PyObject_GC_Track((PyObject *)p); + return p; } CThunkObject *_ctypes_alloc_callback(PyObject *callable, - PyObject *converters, - PyObject *restype, - int flags) + PyObject *converters, + PyObject *restype, + int flags) { - int result; - CThunkObject *p; - Py_ssize_t nArgs, i; - ffi_abi cc; - - nArgs = PySequence_Size(converters); - p = CThunkObject_new(nArgs); - if (p == NULL) - return NULL; - - assert(CThunk_CheckExact((PyObject *)p)); - - p->pcl = _ctypes_alloc_closure(); - if (p->pcl == NULL) { - PyErr_NoMemory(); - goto error; - } - - p->flags = flags; - for (i = 0; i < nArgs; ++i) { - PyObject *cnv = PySequence_GetItem(converters, i); - if (cnv == NULL) - goto error; - p->atypes[i] = _ctypes_get_ffi_type(cnv); - Py_DECREF(cnv); - } - p->atypes[i] = NULL; - - Py_INCREF(restype); - p->restype = restype; - if (restype == Py_None) { - p->setfunc = NULL; - p->ffi_restype = &ffi_type_void; - } else { - StgDictObject *dict = PyType_stgdict(restype); - if (dict == NULL || dict->setfunc == NULL) { - PyErr_SetString(PyExc_TypeError, - "invalid result type for callback function"); - goto error; - } - p->setfunc = dict->setfunc; - p->ffi_restype = &dict->ffi_type_pointer; - } - - cc = FFI_DEFAULT_ABI; + int result; + CThunkObject *p; + Py_ssize_t nArgs, i; + ffi_abi cc; + + nArgs = PySequence_Size(converters); + p = CThunkObject_new(nArgs); + if (p == NULL) + return NULL; + + assert(CThunk_CheckExact((PyObject *)p)); + + p->pcl = _ctypes_alloc_closure(); + if (p->pcl == NULL) { + PyErr_NoMemory(); + goto error; + } + + p->flags = flags; + for (i = 0; i < nArgs; ++i) { + PyObject *cnv = PySequence_GetItem(converters, i); + if (cnv == NULL) + goto error; + p->atypes[i] = _ctypes_get_ffi_type(cnv); + Py_DECREF(cnv); + } + p->atypes[i] = NULL; + + Py_INCREF(restype); + p->restype = restype; + if (restype == Py_None) { + p->setfunc = NULL; + p->ffi_restype = &ffi_type_void; + } else { + StgDictObject *dict = PyType_stgdict(restype); + if (dict == NULL || dict->setfunc == NULL) { + PyErr_SetString(PyExc_TypeError, + "invalid result type for callback function"); + goto error; + } + p->setfunc = dict->setfunc; + p->ffi_restype = &dict->ffi_type_pointer; + } + + cc = FFI_DEFAULT_ABI; #if defined(MS_WIN32) && !defined(_WIN32_WCE) && !defined(MS_WIN64) - if ((flags & FUNCFLAG_CDECL) == 0) - cc = FFI_STDCALL; + if ((flags & FUNCFLAG_CDECL) == 0) + cc = FFI_STDCALL; #endif - result = ffi_prep_cif(&p->cif, cc, - Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int), - _ctypes_get_ffi_type(restype), - &p->atypes[0]); - if (result != FFI_OK) { - PyErr_Format(PyExc_RuntimeError, - "ffi_prep_cif failed with %d", result); - goto error; - } - result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p); - if (result != FFI_OK) { - PyErr_Format(PyExc_RuntimeError, - "ffi_prep_closure failed with %d", result); - goto error; - } - - Py_INCREF(converters); - p->converters = converters; - Py_INCREF(callable); - p->callable = callable; - return p; + result = ffi_prep_cif(&p->cif, cc, + Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int), + _ctypes_get_ffi_type(restype), + &p->atypes[0]); + if (result != FFI_OK) { + PyErr_Format(PyExc_RuntimeError, + "ffi_prep_cif failed with %d", result); + goto error; + } + result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p); + if (result != FFI_OK) { + PyErr_Format(PyExc_RuntimeError, + "ffi_prep_closure failed with %d", result); + goto error; + } + + Py_INCREF(converters); + p->converters = converters; + Py_INCREF(callable); + p->callable = callable; + return p; error: - Py_XDECREF(p); - return NULL; + Py_XDECREF(p); + return NULL; } #ifdef MS_WIN32 static void LoadPython(void) { - if (!Py_IsInitialized()) { + if (!Py_IsInitialized()) { #ifdef WITH_THREAD - PyEval_InitThreads(); + PyEval_InitThreads(); #endif - Py_Initialize(); - } + Py_Initialize(); + } } /******************************************************************/ long Call_GetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv) { - PyObject *mod, *func, *result; - long retval; - static PyObject *context; - - if (context == NULL) - context = PyUnicode_InternFromString("_ctypes.DllGetClassObject"); - - mod = PyImport_ImportModuleNoBlock("ctypes"); - if (!mod) { - PyErr_WriteUnraisable(context ? context : Py_None); - /* There has been a warning before about this already */ - return E_FAIL; - } - - func = PyObject_GetAttrString(mod, "DllGetClassObject"); - Py_DECREF(mod); - if (!func) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - { - PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid); - PyObject *py_riid = PyLong_FromVoidPtr((void *)riid); - PyObject *py_ppv = PyLong_FromVoidPtr(ppv); - if (!py_rclsid || !py_riid || !py_ppv) { - Py_XDECREF(py_rclsid); - Py_XDECREF(py_riid); - Py_XDECREF(py_ppv); - Py_DECREF(func); - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - result = PyObject_CallFunctionObjArgs(func, - py_rclsid, - py_riid, - py_ppv, - NULL); - Py_DECREF(py_rclsid); - Py_DECREF(py_riid); - Py_DECREF(py_ppv); - } - Py_DECREF(func); - if (!result) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - retval = PyLong_AsLong(result); - if (PyErr_Occurred()) { - PyErr_WriteUnraisable(context ? context : Py_None); - retval = E_FAIL; - } - Py_DECREF(result); - return retval; + PyObject *mod, *func, *result; + long retval; + static PyObject *context; + + if (context == NULL) + context = PyUnicode_InternFromString("_ctypes.DllGetClassObject"); + + mod = PyImport_ImportModuleNoBlock("ctypes"); + if (!mod) { + PyErr_WriteUnraisable(context ? context : Py_None); + /* There has been a warning before about this already */ + return E_FAIL; + } + + func = PyObject_GetAttrString(mod, "DllGetClassObject"); + Py_DECREF(mod); + if (!func) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + { + PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid); + PyObject *py_riid = PyLong_FromVoidPtr((void *)riid); + PyObject *py_ppv = PyLong_FromVoidPtr(ppv); + if (!py_rclsid || !py_riid || !py_ppv) { + Py_XDECREF(py_rclsid); + Py_XDECREF(py_riid); + Py_XDECREF(py_ppv); + Py_DECREF(func); + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + result = PyObject_CallFunctionObjArgs(func, + py_rclsid, + py_riid, + py_ppv, + NULL); + Py_DECREF(py_rclsid); + Py_DECREF(py_riid); + Py_DECREF(py_ppv); + } + Py_DECREF(func); + if (!result) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + retval = PyLong_AsLong(result); + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(context ? context : Py_None); + retval = E_FAIL; + } + Py_DECREF(result); + return retval; } STDAPI DllGetClassObject(REFCLSID rclsid, - REFIID riid, - LPVOID *ppv) + REFIID riid, + LPVOID *ppv) { - long result; + long result; #ifdef WITH_THREAD - PyGILState_STATE state; + PyGILState_STATE state; #endif - LoadPython(); + LoadPython(); #ifdef WITH_THREAD - state = PyGILState_Ensure(); + state = PyGILState_Ensure(); #endif - result = Call_GetClassObject(rclsid, riid, ppv); + result = Call_GetClassObject(rclsid, riid, ppv); #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif - return result; + return result; } long Call_CanUnloadNow(void) { - PyObject *mod, *func, *result; - long retval; - static PyObject *context; - - if (context == NULL) - context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow"); - - mod = PyImport_ImportModuleNoBlock("ctypes"); - if (!mod) { -/* OutputDebugString("Could not import ctypes"); */ - /* We assume that this error can only occur when shutting - down, so we silently ignore it */ - PyErr_Clear(); - return E_FAIL; - } - /* Other errors cannot be raised, but are printed to stderr */ - func = PyObject_GetAttrString(mod, "DllCanUnloadNow"); - Py_DECREF(mod); - if (!func) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - result = PyObject_CallFunction(func, NULL); - Py_DECREF(func); - if (!result) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - retval = PyLong_AsLong(result); - if (PyErr_Occurred()) { - PyErr_WriteUnraisable(context ? context : Py_None); - retval = E_FAIL; - } - Py_DECREF(result); - return retval; + PyObject *mod, *func, *result; + long retval; + static PyObject *context; + + if (context == NULL) + context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow"); + + mod = PyImport_ImportModuleNoBlock("ctypes"); + if (!mod) { +/* OutputDebugString("Could not import ctypes"); */ + /* We assume that this error can only occur when shutting + down, so we silently ignore it */ + PyErr_Clear(); + return E_FAIL; + } + /* Other errors cannot be raised, but are printed to stderr */ + func = PyObject_GetAttrString(mod, "DllCanUnloadNow"); + Py_DECREF(mod); + if (!func) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + result = PyObject_CallFunction(func, NULL); + Py_DECREF(func); + if (!result) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + retval = PyLong_AsLong(result); + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(context ? context : Py_None); + retval = E_FAIL; + } + Py_DECREF(result); + return retval; } /* @@ -604,26 +604,26 @@ long Call_CanUnloadNow(void) STDAPI DllCanUnloadNow(void) { - long result; + long result; #ifdef WITH_THREAD - PyGILState_STATE state = PyGILState_Ensure(); + PyGILState_STATE state = PyGILState_Ensure(); #endif - result = Call_CanUnloadNow(); + result = Call_CanUnloadNow(); #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif - return result; + return result; } #ifndef Py_NO_ENABLE_SHARED BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvRes) { - switch(fdwReason) { - case DLL_PROCESS_ATTACH: - DisableThreadLibraryCalls(hinstDLL); - break; - } - return TRUE; + switch(fdwReason) { + case DLL_PROCESS_ATTACH: + DisableThreadLibraryCalls(hinstDLL); + break; + } + return TRUE; } #endif diff --git a/Modules/_ctypes/callproc.c b/Modules/_ctypes/callproc.c index 022cceb..0e4f1b1 100644 --- a/Modules/_ctypes/callproc.c +++ b/Modules/_ctypes/callproc.c @@ -4,9 +4,9 @@ */ /* * Related Work: - * - calldll http://www.nightmare.com/software.html - * - libffi http://sourceware.cygnus.com/libffi/ - * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html + * - calldll http://www.nightmare.com/software.html + * - libffi http://sourceware.cygnus.com/libffi/ + * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html * and, of course, Don Beaudry's MESS package, but this is more ctypes * related. */ @@ -82,17 +82,17 @@ static void pymem_destructor(PyObject *ptr) { - void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM); - if (p) { - PyMem_Free(p); - } + void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM); + if (p) { + PyMem_Free(p); + } } /* ctypes maintains thread-local storage that has space for two error numbers: private copies of the system 'errno' value and, on Windows, the system error code accessed by the GetLastError() and SetLastError() api functions. - + Foreign functions created with CDLL(..., use_errno=True), when called, swap the system 'errno' value with the private copy just before the actual function call, and swapped again immediately afterwards. The 'use_errno' @@ -125,88 +125,88 @@ static void pymem_destructor(PyObject *ptr) PyObject * _ctypes_get_errobj(int **pspace) { - PyObject *dict = PyThreadState_GetDict(); - PyObject *errobj; - static PyObject *error_object_name; - if (dict == 0) { - PyErr_SetString(PyExc_RuntimeError, - "cannot get thread state"); - return NULL; - } - if (error_object_name == NULL) { - error_object_name = PyUnicode_InternFromString("ctypes.error_object"); - if (error_object_name == NULL) - return NULL; - } - errobj = PyDict_GetItem(dict, error_object_name); - if (errobj) { - if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) { - PyErr_SetString(PyExc_RuntimeError, - "ctypes.error_object is an invalid capsule"); - return NULL; - } - Py_INCREF(errobj); - } - else { - void *space = PyMem_Malloc(sizeof(int) * 2); - if (space == NULL) - return NULL; - memset(space, 0, sizeof(int) * 2); - errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); - if (errobj == NULL) - return NULL; - if (-1 == PyDict_SetItem(dict, error_object_name, - errobj)) { - Py_DECREF(errobj); - return NULL; - } - } - *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM); - return errobj; + PyObject *dict = PyThreadState_GetDict(); + PyObject *errobj; + static PyObject *error_object_name; + if (dict == 0) { + PyErr_SetString(PyExc_RuntimeError, + "cannot get thread state"); + return NULL; + } + if (error_object_name == NULL) { + error_object_name = PyUnicode_InternFromString("ctypes.error_object"); + if (error_object_name == NULL) + return NULL; + } + errobj = PyDict_GetItem(dict, error_object_name); + if (errobj) { + if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) { + PyErr_SetString(PyExc_RuntimeError, + "ctypes.error_object is an invalid capsule"); + return NULL; + } + Py_INCREF(errobj); + } + else { + void *space = PyMem_Malloc(sizeof(int) * 2); + if (space == NULL) + return NULL; + memset(space, 0, sizeof(int) * 2); + errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); + if (errobj == NULL) + return NULL; + if (-1 == PyDict_SetItem(dict, error_object_name, + errobj)) { + Py_DECREF(errobj); + return NULL; + } + } + *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM); + return errobj; } static PyObject * get_error_internal(PyObject *self, PyObject *args, int index) { - int *space; - PyObject *errobj = _ctypes_get_errobj(&space); - PyObject *result; - - if (errobj == NULL) - return NULL; - result = PyLong_FromLong(space[index]); - Py_DECREF(errobj); - return result; + int *space; + PyObject *errobj = _ctypes_get_errobj(&space); + PyObject *result; + + if (errobj == NULL) + return NULL; + result = PyLong_FromLong(space[index]); + Py_DECREF(errobj); + return result; } static PyObject * set_error_internal(PyObject *self, PyObject *args, int index) { - int new_errno, old_errno; - PyObject *errobj; - int *space; - - if (!PyArg_ParseTuple(args, "i", &new_errno)) - return NULL; - errobj = _ctypes_get_errobj(&space); - if (errobj == NULL) - return NULL; - old_errno = space[index]; - space[index] = new_errno; - Py_DECREF(errobj); - return PyLong_FromLong(old_errno); + int new_errno, old_errno; + PyObject *errobj; + int *space; + + if (!PyArg_ParseTuple(args, "i", &new_errno)) + return NULL; + errobj = _ctypes_get_errobj(&space); + if (errobj == NULL) + return NULL; + old_errno = space[index]; + space[index] = new_errno; + Py_DECREF(errobj); + return PyLong_FromLong(old_errno); } static PyObject * get_errno(PyObject *self, PyObject *args) { - return get_error_internal(self, args, 0); + return get_error_internal(self, args, 0); } static PyObject * set_errno(PyObject *self, PyObject *args) { - return set_error_internal(self, args, 0); + return set_error_internal(self, args, 0); } #ifdef MS_WIN32 @@ -214,202 +214,202 @@ set_errno(PyObject *self, PyObject *args) static PyObject * get_last_error(PyObject *self, PyObject *args) { - return get_error_internal(self, args, 1); + return get_error_internal(self, args, 1); } static PyObject * set_last_error(PyObject *self, PyObject *args) { - return set_error_internal(self, args, 1); + return set_error_internal(self, args, 1); } PyObject *ComError; static WCHAR *FormatError(DWORD code) { - WCHAR *lpMsgBuf; - DWORD n; - n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - code, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ - (LPWSTR) &lpMsgBuf, - 0, - NULL); - if (n) { - while (iswspace(lpMsgBuf[n-1])) - --n; - lpMsgBuf[n] = L'\0'; /* rstrip() */ - } - return lpMsgBuf; + WCHAR *lpMsgBuf; + DWORD n; + n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + code, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ + (LPWSTR) &lpMsgBuf, + 0, + NULL); + if (n) { + while (iswspace(lpMsgBuf[n-1])) + --n; + lpMsgBuf[n] = L'\0'; /* rstrip() */ + } + return lpMsgBuf; } #ifndef DONT_USE_SEH static void SetException(DWORD code, EXCEPTION_RECORD *pr) { - /* The 'code' is a normal win32 error code so it could be handled by - PyErr_SetFromWindowsErr(). However, for some errors, we have additional - information not included in the error code. We handle those here and - delegate all others to the generic function. */ - switch (code) { - case EXCEPTION_ACCESS_VIOLATION: - /* The thread attempted to read from or write - to a virtual address for which it does not - have the appropriate access. */ - if (pr->ExceptionInformation[0] == 0) - PyErr_Format(PyExc_WindowsError, - "exception: access violation reading %p", - pr->ExceptionInformation[1]); - else - PyErr_Format(PyExc_WindowsError, - "exception: access violation writing %p", - pr->ExceptionInformation[1]); - break; - - case EXCEPTION_BREAKPOINT: - /* A breakpoint was encountered. */ - PyErr_SetString(PyExc_WindowsError, - "exception: breakpoint encountered"); - break; - - case EXCEPTION_DATATYPE_MISALIGNMENT: - /* The thread attempted to read or write data that is - misaligned on hardware that does not provide - alignment. For example, 16-bit values must be - aligned on 2-byte boundaries, 32-bit values on - 4-byte boundaries, and so on. */ - PyErr_SetString(PyExc_WindowsError, - "exception: datatype misalignment"); - break; - - case EXCEPTION_SINGLE_STEP: - /* A trace trap or other single-instruction mechanism - signaled that one instruction has been executed. */ - PyErr_SetString(PyExc_WindowsError, - "exception: single step"); - break; - - case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: - /* The thread attempted to access an array element - that is out of bounds, and the underlying hardware - supports bounds checking. */ - PyErr_SetString(PyExc_WindowsError, - "exception: array bounds exceeded"); - break; - - case EXCEPTION_FLT_DENORMAL_OPERAND: - /* One of the operands in a floating-point operation - is denormal. A denormal value is one that is too - small to represent as a standard floating-point - value. */ - PyErr_SetString(PyExc_WindowsError, - "exception: floating-point operand denormal"); - break; - - case EXCEPTION_FLT_DIVIDE_BY_ZERO: - /* The thread attempted to divide a floating-point - value by a floating-point divisor of zero. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float divide by zero"); - break; - - case EXCEPTION_FLT_INEXACT_RESULT: - /* The result of a floating-point operation cannot be - represented exactly as a decimal fraction. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float inexact"); - break; - - case EXCEPTION_FLT_INVALID_OPERATION: - /* This exception represents any floating-point - exception not included in this list. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float invalid operation"); - break; - - case EXCEPTION_FLT_OVERFLOW: - /* The exponent of a floating-point operation is - greater than the magnitude allowed by the - corresponding type. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float overflow"); - break; - - case EXCEPTION_FLT_STACK_CHECK: - /* The stack overflowed or underflowed as the result - of a floating-point operation. */ - PyErr_SetString(PyExc_WindowsError, - "exception: stack over/underflow"); - break; - - case EXCEPTION_STACK_OVERFLOW: - /* The stack overflowed or underflowed as the result - of a floating-point operation. */ - PyErr_SetString(PyExc_WindowsError, - "exception: stack overflow"); - break; - - case EXCEPTION_FLT_UNDERFLOW: - /* The exponent of a floating-point operation is less - than the magnitude allowed by the corresponding - type. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float underflow"); - break; - - case EXCEPTION_INT_DIVIDE_BY_ZERO: - /* The thread attempted to divide an integer value by - an integer divisor of zero. */ - PyErr_SetString(PyExc_WindowsError, - "exception: integer divide by zero"); - break; - - case EXCEPTION_INT_OVERFLOW: - /* The result of an integer operation caused a carry - out of the most significant bit of the result. */ - PyErr_SetString(PyExc_WindowsError, - "exception: integer overflow"); - break; - - case EXCEPTION_PRIV_INSTRUCTION: - /* The thread attempted to execute an instruction - whose operation is not allowed in the current - machine mode. */ - PyErr_SetString(PyExc_WindowsError, - "exception: priviledged instruction"); - break; - - case EXCEPTION_NONCONTINUABLE_EXCEPTION: - /* The thread attempted to continue execution after a - noncontinuable exception occurred. */ - PyErr_SetString(PyExc_WindowsError, - "exception: nocontinuable"); - break; - - default: - PyErr_SetFromWindowsErr(code); - break; - } + /* The 'code' is a normal win32 error code so it could be handled by + PyErr_SetFromWindowsErr(). However, for some errors, we have additional + information not included in the error code. We handle those here and + delegate all others to the generic function. */ + switch (code) { + case EXCEPTION_ACCESS_VIOLATION: + /* The thread attempted to read from or write + to a virtual address for which it does not + have the appropriate access. */ + if (pr->ExceptionInformation[0] == 0) + PyErr_Format(PyExc_WindowsError, + "exception: access violation reading %p", + pr->ExceptionInformation[1]); + else + PyErr_Format(PyExc_WindowsError, + "exception: access violation writing %p", + pr->ExceptionInformation[1]); + break; + + case EXCEPTION_BREAKPOINT: + /* A breakpoint was encountered. */ + PyErr_SetString(PyExc_WindowsError, + "exception: breakpoint encountered"); + break; + + case EXCEPTION_DATATYPE_MISALIGNMENT: + /* The thread attempted to read or write data that is + misaligned on hardware that does not provide + alignment. For example, 16-bit values must be + aligned on 2-byte boundaries, 32-bit values on + 4-byte boundaries, and so on. */ + PyErr_SetString(PyExc_WindowsError, + "exception: datatype misalignment"); + break; + + case EXCEPTION_SINGLE_STEP: + /* A trace trap or other single-instruction mechanism + signaled that one instruction has been executed. */ + PyErr_SetString(PyExc_WindowsError, + "exception: single step"); + break; + + case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: + /* The thread attempted to access an array element + that is out of bounds, and the underlying hardware + supports bounds checking. */ + PyErr_SetString(PyExc_WindowsError, + "exception: array bounds exceeded"); + break; + + case EXCEPTION_FLT_DENORMAL_OPERAND: + /* One of the operands in a floating-point operation + is denormal. A denormal value is one that is too + small to represent as a standard floating-point + value. */ + PyErr_SetString(PyExc_WindowsError, + "exception: floating-point operand denormal"); + break; + + case EXCEPTION_FLT_DIVIDE_BY_ZERO: + /* The thread attempted to divide a floating-point + value by a floating-point divisor of zero. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float divide by zero"); + break; + + case EXCEPTION_FLT_INEXACT_RESULT: + /* The result of a floating-point operation cannot be + represented exactly as a decimal fraction. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float inexact"); + break; + + case EXCEPTION_FLT_INVALID_OPERATION: + /* This exception represents any floating-point + exception not included in this list. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float invalid operation"); + break; + + case EXCEPTION_FLT_OVERFLOW: + /* The exponent of a floating-point operation is + greater than the magnitude allowed by the + corresponding type. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float overflow"); + break; + + case EXCEPTION_FLT_STACK_CHECK: + /* The stack overflowed or underflowed as the result + of a floating-point operation. */ + PyErr_SetString(PyExc_WindowsError, + "exception: stack over/underflow"); + break; + + case EXCEPTION_STACK_OVERFLOW: + /* The stack overflowed or underflowed as the result + of a floating-point operation. */ + PyErr_SetString(PyExc_WindowsError, + "exception: stack overflow"); + break; + + case EXCEPTION_FLT_UNDERFLOW: + /* The exponent of a floating-point operation is less + than the magnitude allowed by the corresponding + type. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float underflow"); + break; + + case EXCEPTION_INT_DIVIDE_BY_ZERO: + /* The thread attempted to divide an integer value by + an integer divisor of zero. */ + PyErr_SetString(PyExc_WindowsError, + "exception: integer divide by zero"); + break; + + case EXCEPTION_INT_OVERFLOW: + /* The result of an integer operation caused a carry + out of the most significant bit of the result. */ + PyErr_SetString(PyExc_WindowsError, + "exception: integer overflow"); + break; + + case EXCEPTION_PRIV_INSTRUCTION: + /* The thread attempted to execute an instruction + whose operation is not allowed in the current + machine mode. */ + PyErr_SetString(PyExc_WindowsError, + "exception: priviledged instruction"); + break; + + case EXCEPTION_NONCONTINUABLE_EXCEPTION: + /* The thread attempted to continue execution after a + noncontinuable exception occurred. */ + PyErr_SetString(PyExc_WindowsError, + "exception: nocontinuable"); + break; + + default: + PyErr_SetFromWindowsErr(code); + break; + } } static DWORD HandleException(EXCEPTION_POINTERS *ptrs, - DWORD *pdw, EXCEPTION_RECORD *record) + DWORD *pdw, EXCEPTION_RECORD *record) { - *pdw = ptrs->ExceptionRecord->ExceptionCode; - *record = *ptrs->ExceptionRecord; - return EXCEPTION_EXECUTE_HANDLER; + *pdw = ptrs->ExceptionRecord->ExceptionCode; + *record = *ptrs->ExceptionRecord; + return EXCEPTION_EXECUTE_HANDLER; } #endif static PyObject * check_hresult(PyObject *self, PyObject *args) { - HRESULT hr; - if (!PyArg_ParseTuple(args, "i", &hr)) - return NULL; - if (FAILED(hr)) - return PyErr_SetFromWindowsErr(hr); - return PyLong_FromLong(hr); + HRESULT hr; + if (!PyArg_ParseTuple(args, "i", &hr)) + return NULL; + if (FAILED(hr)) + return PyErr_SetFromWindowsErr(hr); + return PyLong_FromLong(hr); } #endif @@ -419,132 +419,132 @@ check_hresult(PyObject *self, PyObject *args) PyCArgObject * PyCArgObject_new(void) { - PyCArgObject *p; - p = PyObject_New(PyCArgObject, &PyCArg_Type); - if (p == NULL) - return NULL; - p->pffi_type = NULL; - p->tag = '\0'; - p->obj = NULL; - memset(&p->value, 0, sizeof(p->value)); - return p; + PyCArgObject *p; + p = PyObject_New(PyCArgObject, &PyCArg_Type); + if (p == NULL) + return NULL; + p->pffi_type = NULL; + p->tag = '\0'; + p->obj = NULL; + memset(&p->value, 0, sizeof(p->value)); + return p; } static void PyCArg_dealloc(PyCArgObject *self) { - Py_XDECREF(self->obj); - PyObject_Del(self); + Py_XDECREF(self->obj); + PyObject_Del(self); } static PyObject * PyCArg_repr(PyCArgObject *self) { - char buffer[256]; - switch(self->tag) { - case 'b': - case 'B': - sprintf(buffer, "<cparam '%c' (%d)>", - self->tag, self->value.b); - break; - case 'h': - case 'H': - sprintf(buffer, "<cparam '%c' (%d)>", - self->tag, self->value.h); - break; - case 'i': - case 'I': - sprintf(buffer, "<cparam '%c' (%d)>", - self->tag, self->value.i); - break; - case 'l': - case 'L': - sprintf(buffer, "<cparam '%c' (%ld)>", - self->tag, self->value.l); - break; - + char buffer[256]; + switch(self->tag) { + case 'b': + case 'B': + sprintf(buffer, "<cparam '%c' (%d)>", + self->tag, self->value.b); + break; + case 'h': + case 'H': + sprintf(buffer, "<cparam '%c' (%d)>", + self->tag, self->value.h); + break; + case 'i': + case 'I': + sprintf(buffer, "<cparam '%c' (%d)>", + self->tag, self->value.i); + break; + case 'l': + case 'L': + sprintf(buffer, "<cparam '%c' (%ld)>", + self->tag, self->value.l); + break; + #ifdef HAVE_LONG_LONG - case 'q': - case 'Q': - sprintf(buffer, + case 'q': + case 'Q': + sprintf(buffer, #ifdef MS_WIN32 - "<cparam '%c' (%I64d)>", + "<cparam '%c' (%I64d)>", #else - "<cparam '%c' (%qd)>", + "<cparam '%c' (%qd)>", #endif - self->tag, self->value.q); - break; + self->tag, self->value.q); + break; #endif - case 'd': - sprintf(buffer, "<cparam '%c' (%f)>", - self->tag, self->value.d); - break; - case 'f': - sprintf(buffer, "<cparam '%c' (%f)>", - self->tag, self->value.f); - break; - - case 'c': - sprintf(buffer, "<cparam '%c' (%c)>", - self->tag, self->value.c); - break; + case 'd': + sprintf(buffer, "<cparam '%c' (%f)>", + self->tag, self->value.d); + break; + case 'f': + sprintf(buffer, "<cparam '%c' (%f)>", + self->tag, self->value.f); + break; + + case 'c': + sprintf(buffer, "<cparam '%c' (%c)>", + self->tag, self->value.c); + break; /* Hm, are these 'z' and 'Z' codes useful at all? Shouldn't they be replaced by the functionality of c_string and c_wstring ? */ - case 'z': - case 'Z': - case 'P': - sprintf(buffer, "<cparam '%c' (%p)>", - self->tag, self->value.p); - break; - - default: - sprintf(buffer, "<cparam '%c' at %p>", - self->tag, self); - break; - } - return PyUnicode_FromString(buffer); + case 'z': + case 'Z': + case 'P': + sprintf(buffer, "<cparam '%c' (%p)>", + self->tag, self->value.p); + break; + + default: + sprintf(buffer, "<cparam '%c' at %p>", + self->tag, self); + break; + } + return PyUnicode_FromString(buffer); } static PyMemberDef PyCArgType_members[] = { - { "_obj", T_OBJECT, - offsetof(PyCArgObject, obj), READONLY, - "the wrapped object" }, - { NULL }, + { "_obj", T_OBJECT, + offsetof(PyCArgObject, obj), READONLY, + "the wrapped object" }, + { NULL }, }; PyTypeObject PyCArg_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "CArgObject", - sizeof(PyCArgObject), - 0, - (destructor)PyCArg_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)PyCArg_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - PyCArgType_members, /* tp_members */ + PyVarObject_HEAD_INIT(NULL, 0) + "CArgObject", + sizeof(PyCArgObject), + 0, + (destructor)PyCArg_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)PyCArg_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + PyCArgType_members, /* tp_members */ }; /****************************************************************/ @@ -577,24 +577,24 @@ PyTypeObject PyCArg_Type = { */ union result { - char c; - char b; - short h; - int i; - long l; + char c; + char b; + short h; + int i; + long l; #ifdef HAVE_LONG_LONG - PY_LONG_LONG q; + PY_LONG_LONG q; #endif - long double D; - double d; - float f; - void *p; + long double D; + double d; + float f; + void *p; }; struct argument { - ffi_type *ffi_type; - PyObject *keep; - union result value; + ffi_type *ffi_type; + PyObject *keep; + union result value; }; /* @@ -602,134 +602,134 @@ struct argument { */ static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa) { - StgDictObject *dict; - pa->keep = NULL; /* so we cannot forget it later */ - - dict = PyObject_stgdict(obj); - if (dict) { - PyCArgObject *carg; - assert(dict->paramfunc); - /* If it has an stgdict, it is a CDataObject */ - carg = dict->paramfunc((CDataObject *)obj); - pa->ffi_type = carg->pffi_type; - memcpy(&pa->value, &carg->value, sizeof(pa->value)); - pa->keep = (PyObject *)carg; - return 0; - } - - if (PyCArg_CheckExact(obj)) { - PyCArgObject *carg = (PyCArgObject *)obj; - pa->ffi_type = carg->pffi_type; - Py_INCREF(obj); - pa->keep = obj; - memcpy(&pa->value, &carg->value, sizeof(pa->value)); - return 0; - } - - /* check for None, integer, string or unicode and use directly if successful */ - if (obj == Py_None) { - pa->ffi_type = &ffi_type_pointer; - pa->value.p = NULL; - return 0; - } - - if (PyLong_Check(obj)) { - pa->ffi_type = &ffi_type_sint; - pa->value.i = (long)PyLong_AsUnsignedLong(obj); - if (pa->value.i == -1 && PyErr_Occurred()) { - PyErr_Clear(); - pa->value.i = PyLong_AsLong(obj); - if (pa->value.i == -1 && PyErr_Occurred()) { - PyErr_SetString(PyExc_OverflowError, - "long int too long to convert"); - return -1; - } - } - return 0; - } - - if (PyBytes_Check(obj)) { - pa->ffi_type = &ffi_type_pointer; - pa->value.p = PyBytes_AsString(obj); - Py_INCREF(obj); - pa->keep = obj; - return 0; - } + StgDictObject *dict; + pa->keep = NULL; /* so we cannot forget it later */ + + dict = PyObject_stgdict(obj); + if (dict) { + PyCArgObject *carg; + assert(dict->paramfunc); + /* If it has an stgdict, it is a CDataObject */ + carg = dict->paramfunc((CDataObject *)obj); + pa->ffi_type = carg->pffi_type; + memcpy(&pa->value, &carg->value, sizeof(pa->value)); + pa->keep = (PyObject *)carg; + return 0; + } + + if (PyCArg_CheckExact(obj)) { + PyCArgObject *carg = (PyCArgObject *)obj; + pa->ffi_type = carg->pffi_type; + Py_INCREF(obj); + pa->keep = obj; + memcpy(&pa->value, &carg->value, sizeof(pa->value)); + return 0; + } + + /* check for None, integer, string or unicode and use directly if successful */ + if (obj == Py_None) { + pa->ffi_type = &ffi_type_pointer; + pa->value.p = NULL; + return 0; + } + + if (PyLong_Check(obj)) { + pa->ffi_type = &ffi_type_sint; + pa->value.i = (long)PyLong_AsUnsignedLong(obj); + if (pa->value.i == -1 && PyErr_Occurred()) { + PyErr_Clear(); + pa->value.i = PyLong_AsLong(obj); + if (pa->value.i == -1 && PyErr_Occurred()) { + PyErr_SetString(PyExc_OverflowError, + "long int too long to convert"); + return -1; + } + } + return 0; + } + + if (PyBytes_Check(obj)) { + pa->ffi_type = &ffi_type_pointer; + pa->value.p = PyBytes_AsString(obj); + Py_INCREF(obj); + pa->keep = obj; + return 0; + } #ifdef CTYPES_UNICODE - if (PyUnicode_Check(obj)) { + if (PyUnicode_Check(obj)) { #ifdef HAVE_USABLE_WCHAR_T - pa->ffi_type = &ffi_type_pointer; - pa->value.p = PyUnicode_AS_UNICODE(obj); - Py_INCREF(obj); - pa->keep = obj; - return 0; + pa->ffi_type = &ffi_type_pointer; + pa->value.p = PyUnicode_AS_UNICODE(obj); + Py_INCREF(obj); + pa->keep = obj; + return 0; #else - int size = PyUnicode_GET_SIZE(obj); - pa->ffi_type = &ffi_type_pointer; - size += 1; /* terminating NUL */ - size *= sizeof(wchar_t); - pa->value.p = PyMem_Malloc(size); - if (!pa->value.p) { - PyErr_NoMemory(); - return -1; - } - memset(pa->value.p, 0, size); - pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); - if (!pa->keep) { - PyMem_Free(pa->value.p); - return -1; - } - if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj, - pa->value.p, PyUnicode_GET_SIZE(obj))) - return -1; - return 0; + int size = PyUnicode_GET_SIZE(obj); + pa->ffi_type = &ffi_type_pointer; + size += 1; /* terminating NUL */ + size *= sizeof(wchar_t); + pa->value.p = PyMem_Malloc(size); + if (!pa->value.p) { + PyErr_NoMemory(); + return -1; + } + memset(pa->value.p, 0, size); + pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); + if (!pa->keep) { + PyMem_Free(pa->value.p); + return -1; + } + if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj, + pa->value.p, PyUnicode_GET_SIZE(obj))) + return -1; + return 0; #endif - } + } #endif - { - PyObject *arg; - arg = PyObject_GetAttrString(obj, "_as_parameter_"); - /* Which types should we exactly allow here? - integers are required for using Python classes - as parameters (they have to expose the '_as_parameter_' - attribute) - */ - if (arg) { - int result; - result = ConvParam(arg, index, pa); - Py_DECREF(arg); - return result; - } - PyErr_Format(PyExc_TypeError, - "Don't know how to convert parameter %d", - Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); - return -1; - } + { + PyObject *arg; + arg = PyObject_GetAttrString(obj, "_as_parameter_"); + /* Which types should we exactly allow here? + integers are required for using Python classes + as parameters (they have to expose the '_as_parameter_' + attribute) + */ + if (arg) { + int result; + result = ConvParam(arg, index, pa); + Py_DECREF(arg); + return result; + } + PyErr_Format(PyExc_TypeError, + "Don't know how to convert parameter %d", + Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); + return -1; + } } ffi_type *_ctypes_get_ffi_type(PyObject *obj) { - StgDictObject *dict; - if (obj == NULL) - return &ffi_type_sint; - dict = PyType_stgdict(obj); - if (dict == NULL) - return &ffi_type_sint; + StgDictObject *dict; + if (obj == NULL) + return &ffi_type_sint; + dict = PyType_stgdict(obj); + if (dict == NULL) + return &ffi_type_sint; #if defined(MS_WIN32) && !defined(_WIN32_WCE) - /* This little trick works correctly with MSVC. - It returns small structures in registers - */ - if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) { - if (dict->ffi_type_pointer.size <= 4) - return &ffi_type_sint32; - else if (dict->ffi_type_pointer.size <= 8) - return &ffi_type_sint64; - } + /* This little trick works correctly with MSVC. + It returns small structures in registers + */ + if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) { + if (dict->ffi_type_pointer.size <= 4) + return &ffi_type_sint32; + else if (dict->ffi_type_pointer.size <= 8) + return &ffi_type_sint64; + } #endif - return &dict->ffi_type_pointer; + return &dict->ffi_type_pointer; } @@ -737,7 +737,7 @@ ffi_type *_ctypes_get_ffi_type(PyObject *obj) * libffi uses: * * ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, - * unsigned int nargs, + * unsigned int nargs, * ffi_type *rtype, * ffi_type **atypes); * @@ -746,139 +746,139 @@ ffi_type *_ctypes_get_ffi_type(PyObject *obj) * void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues); */ static int _call_function_pointer(int flags, - PPROC pProc, - void **avalues, - ffi_type **atypes, - ffi_type *restype, - void *resmem, - int argcount) + PPROC pProc, + void **avalues, + ffi_type **atypes, + ffi_type *restype, + void *resmem, + int argcount) { #ifdef WITH_THREAD - PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */ + PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */ #endif - PyObject *error_object = NULL; - int *space; - ffi_cif cif; - int cc; + PyObject *error_object = NULL; + int *space; + ffi_cif cif; + int cc; #ifdef MS_WIN32 - int delta; + int delta; #ifndef DONT_USE_SEH - DWORD dwExceptionCode = 0; - EXCEPTION_RECORD record; + DWORD dwExceptionCode = 0; + EXCEPTION_RECORD record; #endif #endif - /* XXX check before here */ - if (restype == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "No ffi_type for result"); - return -1; - } - - cc = FFI_DEFAULT_ABI; + /* XXX check before here */ + if (restype == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "No ffi_type for result"); + return -1; + } + + cc = FFI_DEFAULT_ABI; #if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE) - if ((flags & FUNCFLAG_CDECL) == 0) - cc = FFI_STDCALL; + if ((flags & FUNCFLAG_CDECL) == 0) + cc = FFI_STDCALL; #endif - if (FFI_OK != ffi_prep_cif(&cif, - cc, - argcount, - restype, - atypes)) { - PyErr_SetString(PyExc_RuntimeError, - "ffi_prep_cif failed"); - return -1; - } - - if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { - error_object = _ctypes_get_errobj(&space); - if (error_object == NULL) - return -1; - } + if (FFI_OK != ffi_prep_cif(&cif, + cc, + argcount, + restype, + atypes)) { + PyErr_SetString(PyExc_RuntimeError, + "ffi_prep_cif failed"); + return -1; + } + + if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { + error_object = _ctypes_get_errobj(&space); + if (error_object == NULL) + return -1; + } #ifdef WITH_THREAD - if ((flags & FUNCFLAG_PYTHONAPI) == 0) - Py_UNBLOCK_THREADS + if ((flags & FUNCFLAG_PYTHONAPI) == 0) + Py_UNBLOCK_THREADS #endif - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } #ifdef MS_WIN32 - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } #ifndef DONT_USE_SEH - __try { + __try { #endif - delta = + delta = #endif - ffi_call(&cif, (void *)pProc, resmem, avalues); + ffi_call(&cif, (void *)pProc, resmem, avalues); #ifdef MS_WIN32 #ifndef DONT_USE_SEH - } - __except (HandleException(GetExceptionInformation(), - &dwExceptionCode, &record)) { - ; - } + } + __except (HandleException(GetExceptionInformation(), + &dwExceptionCode, &record)) { + ; + } #endif - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } #endif - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } - Py_XDECREF(error_object); + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } + Py_XDECREF(error_object); #ifdef WITH_THREAD - if ((flags & FUNCFLAG_PYTHONAPI) == 0) - Py_BLOCK_THREADS + if ((flags & FUNCFLAG_PYTHONAPI) == 0) + Py_BLOCK_THREADS #endif #ifdef MS_WIN32 #ifndef DONT_USE_SEH - if (dwExceptionCode) { - SetException(dwExceptionCode, &record); - return -1; - } + if (dwExceptionCode) { + SetException(dwExceptionCode, &record); + return -1; + } #endif #ifdef MS_WIN64 - if (delta != 0) { - PyErr_Format(PyExc_RuntimeError, - "ffi_call failed with code %d", - delta); - return -1; - } + if (delta != 0) { + PyErr_Format(PyExc_RuntimeError, + "ffi_call failed with code %d", + delta); + return -1; + } #else - if (delta < 0) { - if (flags & FUNCFLAG_CDECL) - PyErr_Format(PyExc_ValueError, - "Procedure called with not enough " - "arguments (%d bytes missing) " - "or wrong calling convention", - -delta); - else - PyErr_Format(PyExc_ValueError, - "Procedure probably called with not enough " - "arguments (%d bytes missing)", - -delta); - return -1; - } else if (delta > 0) { - PyErr_Format(PyExc_ValueError, - "Procedure probably called with too many " - "arguments (%d bytes in excess)", - delta); - return -1; - } + if (delta < 0) { + if (flags & FUNCFLAG_CDECL) + PyErr_Format(PyExc_ValueError, + "Procedure called with not enough " + "arguments (%d bytes missing) " + "or wrong calling convention", + -delta); + else + PyErr_Format(PyExc_ValueError, + "Procedure probably called with not enough " + "arguments (%d bytes missing)", + -delta); + return -1; + } else if (delta > 0) { + PyErr_Format(PyExc_ValueError, + "Procedure probably called with too many " + "arguments (%d bytes in excess)", + delta); + return -1; + } #endif #endif - if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred()) - return -1; - return 0; + if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred()) + return -1; + return 0; } /* @@ -893,41 +893,41 @@ static int _call_function_pointer(int flags, */ static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker) { - StgDictObject *dict; - PyObject *retval, *v; - - if (restype == NULL) - return PyLong_FromLong(*(int *)result); - - if (restype == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - - dict = PyType_stgdict(restype); - if (dict == NULL) - return PyObject_CallFunction(restype, "i", *(int *)result); - - if (dict->getfunc && !_ctypes_simple_instance(restype)) { - retval = dict->getfunc(result, dict->size); - /* If restype is py_object (detected by comparing getfunc with - O_get), we have to call Py_DECREF because O_get has already - called Py_INCREF. - */ - if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) { - Py_DECREF(retval); - } - } else - retval = PyCData_FromBaseObj(restype, NULL, 0, result); - - if (!checker || !retval) - return retval; - - v = PyObject_CallFunctionObjArgs(checker, retval, NULL); - if (v == NULL) - _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2); - Py_DECREF(retval); - return v; + StgDictObject *dict; + PyObject *retval, *v; + + if (restype == NULL) + return PyLong_FromLong(*(int *)result); + + if (restype == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + + dict = PyType_stgdict(restype); + if (dict == NULL) + return PyObject_CallFunction(restype, "i", *(int *)result); + + if (dict->getfunc && !_ctypes_simple_instance(restype)) { + retval = dict->getfunc(result, dict->size); + /* If restype is py_object (detected by comparing getfunc with + O_get), we have to call Py_DECREF because O_get has already + called Py_INCREF. + */ + if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) { + Py_DECREF(retval); + } + } else + retval = PyCData_FromBaseObj(restype, NULL, 0, result); + + if (!checker || !retval) + return retval; + + v = PyObject_CallFunctionObjArgs(checker, retval, NULL); + if (v == NULL) + _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2); + Py_DECREF(retval); + return v; } /* @@ -936,40 +936,40 @@ static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker) */ void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...) { - va_list vargs; - PyObject *tp, *v, *tb, *s, *cls_str, *msg_str; - - va_start(vargs, fmt); - s = PyUnicode_FromFormatV(fmt, vargs); - va_end(vargs); - if (!s) - return; - - PyErr_Fetch(&tp, &v, &tb); - PyErr_NormalizeException(&tp, &v, &tb); - cls_str = PyObject_Str(tp); - if (cls_str) { - PyUnicode_AppendAndDel(&s, cls_str); - PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": ")); - if (s == NULL) - goto error; - } else - PyErr_Clear(); - msg_str = PyObject_Str(v); - if (msg_str) - PyUnicode_AppendAndDel(&s, msg_str); - else { - PyErr_Clear(); - PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???")); - if (s == NULL) - goto error; - } - PyErr_SetObject(exc_class, s); + va_list vargs; + PyObject *tp, *v, *tb, *s, *cls_str, *msg_str; + + va_start(vargs, fmt); + s = PyUnicode_FromFormatV(fmt, vargs); + va_end(vargs); + if (!s) + return; + + PyErr_Fetch(&tp, &v, &tb); + PyErr_NormalizeException(&tp, &v, &tb); + cls_str = PyObject_Str(tp); + if (cls_str) { + PyUnicode_AppendAndDel(&s, cls_str); + PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": ")); + if (s == NULL) + goto error; + } else + PyErr_Clear(); + msg_str = PyObject_Str(v); + if (msg_str) + PyUnicode_AppendAndDel(&s, msg_str); + else { + PyErr_Clear(); + PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???")); + if (s == NULL) + goto error; + } + PyErr_SetObject(exc_class, s); error: - Py_XDECREF(tp); - Py_XDECREF(v); - Py_XDECREF(tb); - Py_XDECREF(s); + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + Py_XDECREF(s); } @@ -978,73 +978,73 @@ error: static PyObject * GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk) { - HRESULT hr; - ISupportErrorInfo *psei = NULL; - IErrorInfo *pei = NULL; - BSTR descr=NULL, helpfile=NULL, source=NULL; - GUID guid; - DWORD helpcontext=0; - LPOLESTR progid; - PyObject *obj; - LPOLESTR text; - - /* We absolutely have to release the GIL during COM method calls, - otherwise we may get a deadlock! - */ + HRESULT hr; + ISupportErrorInfo *psei = NULL; + IErrorInfo *pei = NULL; + BSTR descr=NULL, helpfile=NULL, source=NULL; + GUID guid; + DWORD helpcontext=0; + LPOLESTR progid; + PyObject *obj; + LPOLESTR text; + + /* We absolutely have to release the GIL during COM method calls, + otherwise we may get a deadlock! + */ #ifdef WITH_THREAD - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #endif - hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei); - if (FAILED(hr)) - goto failed; + hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei); + if (FAILED(hr)) + goto failed; - hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid); - psei->lpVtbl->Release(psei); - if (FAILED(hr)) - goto failed; + hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid); + psei->lpVtbl->Release(psei); + if (FAILED(hr)) + goto failed; - hr = GetErrorInfo(0, &pei); - if (hr != S_OK) - goto failed; + hr = GetErrorInfo(0, &pei); + if (hr != S_OK) + goto failed; - pei->lpVtbl->GetDescription(pei, &descr); - pei->lpVtbl->GetGUID(pei, &guid); - pei->lpVtbl->GetHelpContext(pei, &helpcontext); - pei->lpVtbl->GetHelpFile(pei, &helpfile); - pei->lpVtbl->GetSource(pei, &source); + pei->lpVtbl->GetDescription(pei, &descr); + pei->lpVtbl->GetGUID(pei, &guid); + pei->lpVtbl->GetHelpContext(pei, &helpcontext); + pei->lpVtbl->GetHelpFile(pei, &helpfile); + pei->lpVtbl->GetSource(pei, &source); - pei->lpVtbl->Release(pei); + pei->lpVtbl->Release(pei); failed: #ifdef WITH_THREAD - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS #endif - progid = NULL; - ProgIDFromCLSID(&guid, &progid); - - text = FormatError(errcode); - obj = Py_BuildValue( - "iu(uuuiu)", - errcode, - text, - descr, source, helpfile, helpcontext, - progid); - if (obj) { - PyErr_SetObject(ComError, obj); - Py_DECREF(obj); - } - LocalFree(text); - - if (descr) - SysFreeString(descr); - if (helpfile) - SysFreeString(helpfile); - if (source) - SysFreeString(source); - - return NULL; + progid = NULL; + ProgIDFromCLSID(&guid, &progid); + + text = FormatError(errcode); + obj = Py_BuildValue( + "iu(uuuiu)", + errcode, + text, + descr, source, helpfile, helpcontext, + progid); + if (obj) { + PyErr_SetObject(ComError, obj); + Py_DECREF(obj); + } + LocalFree(text); + + if (descr) + SysFreeString(descr); + if (helpfile) + SysFreeString(helpfile); + if (source) + SysFreeString(source); + + return NULL; } #endif @@ -1056,158 +1056,158 @@ GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk) * - XXX various requirements for restype, not yet collected */ PyObject *_ctypes_callproc(PPROC pProc, - PyObject *argtuple, + PyObject *argtuple, #ifdef MS_WIN32 - IUnknown *pIunk, - GUID *iid, + IUnknown *pIunk, + GUID *iid, #endif - int flags, - PyObject *argtypes, /* misleading name: This is a tuple of - methods, not types: the .from_param - class methods of the types */ - PyObject *restype, - PyObject *checker) + int flags, + PyObject *argtypes, /* misleading name: This is a tuple of + methods, not types: the .from_param + class methods of the types */ + PyObject *restype, + PyObject *checker) { - Py_ssize_t i, n, argcount, argtype_count; - void *resbuf; - struct argument *args, *pa; - ffi_type **atypes; - ffi_type *rtype; - void **avalues; - PyObject *retval = NULL; - - n = argcount = PyTuple_GET_SIZE(argtuple); + Py_ssize_t i, n, argcount, argtype_count; + void *resbuf; + struct argument *args, *pa; + ffi_type **atypes; + ffi_type *rtype; + void **avalues; + PyObject *retval = NULL; + + n = argcount = PyTuple_GET_SIZE(argtuple); #ifdef MS_WIN32 - /* an optional COM object this pointer */ - if (pIunk) - ++argcount; + /* an optional COM object this pointer */ + if (pIunk) + ++argcount; #endif - args = (struct argument *)alloca(sizeof(struct argument) * argcount); - if (!args) { - PyErr_NoMemory(); - return NULL; - } - memset(args, 0, sizeof(struct argument) * argcount); - argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0; + args = (struct argument *)alloca(sizeof(struct argument) * argcount); + if (!args) { + PyErr_NoMemory(); + return NULL; + } + memset(args, 0, sizeof(struct argument) * argcount); + argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0; #ifdef MS_WIN32 - if (pIunk) { - args[0].ffi_type = &ffi_type_pointer; - args[0].value.p = pIunk; - pa = &args[1]; - } else + if (pIunk) { + args[0].ffi_type = &ffi_type_pointer; + args[0].value.p = pIunk; + pa = &args[1]; + } else #endif - pa = &args[0]; - - /* Convert the arguments */ - for (i = 0; i < n; ++i, ++pa) { - PyObject *converter; - PyObject *arg; - int err; - - arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */ - /* For cdecl functions, we allow more actual arguments - than the length of the argtypes tuple. - This is checked in _ctypes::PyCFuncPtr_Call - */ - if (argtypes && argtype_count > i) { - PyObject *v; - converter = PyTuple_GET_ITEM(argtypes, i); - v = PyObject_CallFunctionObjArgs(converter, - arg, - NULL); - if (v == NULL) { - _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); - goto cleanup; - } - - err = ConvParam(v, i+1, pa); - Py_DECREF(v); - if (-1 == err) { - _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); - goto cleanup; - } - } else { - err = ConvParam(arg, i+1, pa); - if (-1 == err) { - _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); - goto cleanup; /* leaking ? */ - } - } - } - - rtype = _ctypes_get_ffi_type(restype); - resbuf = alloca(max(rtype->size, sizeof(ffi_arg))); - - avalues = (void **)alloca(sizeof(void *) * argcount); - atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount); - if (!resbuf || !avalues || !atypes) { - PyErr_NoMemory(); - goto cleanup; - } - for (i = 0; i < argcount; ++i) { - atypes[i] = args[i].ffi_type; - if (atypes[i]->type == FFI_TYPE_STRUCT + pa = &args[0]; + + /* Convert the arguments */ + for (i = 0; i < n; ++i, ++pa) { + PyObject *converter; + PyObject *arg; + int err; + + arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */ + /* For cdecl functions, we allow more actual arguments + than the length of the argtypes tuple. + This is checked in _ctypes::PyCFuncPtr_Call + */ + if (argtypes && argtype_count > i) { + PyObject *v; + converter = PyTuple_GET_ITEM(argtypes, i); + v = PyObject_CallFunctionObjArgs(converter, + arg, + NULL); + if (v == NULL) { + _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); + goto cleanup; + } + + err = ConvParam(v, i+1, pa); + Py_DECREF(v); + if (-1 == err) { + _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); + goto cleanup; + } + } else { + err = ConvParam(arg, i+1, pa); + if (-1 == err) { + _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); + goto cleanup; /* leaking ? */ + } + } + } + + rtype = _ctypes_get_ffi_type(restype); + resbuf = alloca(max(rtype->size, sizeof(ffi_arg))); + + avalues = (void **)alloca(sizeof(void *) * argcount); + atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount); + if (!resbuf || !avalues || !atypes) { + PyErr_NoMemory(); + goto cleanup; + } + for (i = 0; i < argcount; ++i) { + atypes[i] = args[i].ffi_type; + if (atypes[i]->type == FFI_TYPE_STRUCT #ifdef _WIN64 - && atypes[i]->size <= sizeof(void *) + && atypes[i]->size <= sizeof(void *) #endif - ) - avalues[i] = (void *)args[i].value.p; - else - avalues[i] = (void *)&args[i].value; - } - - if (-1 == _call_function_pointer(flags, pProc, avalues, atypes, - rtype, resbuf, - Py_SAFE_DOWNCAST(argcount, - Py_ssize_t, - int))) - goto cleanup; + ) + avalues[i] = (void *)args[i].value.p; + else + avalues[i] = (void *)&args[i].value; + } + + if (-1 == _call_function_pointer(flags, pProc, avalues, atypes, + rtype, resbuf, + Py_SAFE_DOWNCAST(argcount, + Py_ssize_t, + int))) + goto cleanup; #ifdef WORDS_BIGENDIAN - /* libffi returns the result in a buffer with sizeof(ffi_arg). This - causes problems on big endian machines, since the result buffer - address cannot simply be used as result pointer, instead we must - adjust the pointer value: - */ - /* - XXX I should find out and clarify why this is needed at all, - especially why adjusting for ffi_type_float must be avoided on - 64-bit platforms. - */ - if (rtype->type != FFI_TYPE_FLOAT - && rtype->type != FFI_TYPE_STRUCT - && rtype->size < sizeof(ffi_arg)) - resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size; + /* libffi returns the result in a buffer with sizeof(ffi_arg). This + causes problems on big endian machines, since the result buffer + address cannot simply be used as result pointer, instead we must + adjust the pointer value: + */ + /* + XXX I should find out and clarify why this is needed at all, + especially why adjusting for ffi_type_float must be avoided on + 64-bit platforms. + */ + if (rtype->type != FFI_TYPE_FLOAT + && rtype->type != FFI_TYPE_STRUCT + && rtype->size < sizeof(ffi_arg)) + resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size; #endif #ifdef MS_WIN32 - if (iid && pIunk) { - if (*(int *)resbuf & 0x80000000) - retval = GetComError(*(HRESULT *)resbuf, iid, pIunk); - else - retval = PyLong_FromLong(*(int *)resbuf); - } else if (flags & FUNCFLAG_HRESULT) { - if (*(int *)resbuf & 0x80000000) - retval = PyErr_SetFromWindowsErr(*(int *)resbuf); - else - retval = PyLong_FromLong(*(int *)resbuf); - } else + if (iid && pIunk) { + if (*(int *)resbuf & 0x80000000) + retval = GetComError(*(HRESULT *)resbuf, iid, pIunk); + else + retval = PyLong_FromLong(*(int *)resbuf); + } else if (flags & FUNCFLAG_HRESULT) { + if (*(int *)resbuf & 0x80000000) + retval = PyErr_SetFromWindowsErr(*(int *)resbuf); + else + retval = PyLong_FromLong(*(int *)resbuf); + } else #endif - retval = GetResult(restype, resbuf, checker); + retval = GetResult(restype, resbuf, checker); cleanup: - for (i = 0; i < argcount; ++i) - Py_XDECREF(args[i].keep); - return retval; + for (i = 0; i < argcount; ++i) + Py_XDECREF(args[i].keep); + return retval; } static int _parse_voidp(PyObject *obj, void **address) { - *address = PyLong_AsVoidPtr(obj); - if (*address == NULL) - return 0; - return 1; + *address = PyLong_AsVoidPtr(obj); + if (*address == NULL) + return 0; + return 1; } #ifdef MS_WIN32 @@ -1219,21 +1219,21 @@ Convert a win32 error code into a string. If the error code is not\n\ given, the return value of a call to GetLastError() is used.\n"; static PyObject *format_error(PyObject *self, PyObject *args) { - PyObject *result; - wchar_t *lpMsgBuf; - DWORD code = 0; - if (!PyArg_ParseTuple(args, "|i:FormatError", &code)) - return NULL; - if (code == 0) - code = GetLastError(); - lpMsgBuf = FormatError(code); - if (lpMsgBuf) { - result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf)); - LocalFree(lpMsgBuf); - } else { - result = PyUnicode_FromString("<no description>"); - } - return result; + PyObject *result; + wchar_t *lpMsgBuf; + DWORD code = 0; + if (!PyArg_ParseTuple(args, "|i:FormatError", &code)) + return NULL; + if (code == 0) + code = GetLastError(); + lpMsgBuf = FormatError(code); + if (lpMsgBuf) { + result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf)); + LocalFree(lpMsgBuf); + } else { + result = PyUnicode_FromString("<no description>"); + } + return result; } static char load_library_doc[] = @@ -1244,24 +1244,24 @@ The handle may be used to locate exported functions in this\n\ module.\n"; static PyObject *load_library(PyObject *self, PyObject *args) { - WCHAR *name; - PyObject *nameobj; - PyObject *ignored; - HMODULE hMod; - if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored)) - return NULL; - - name = PyUnicode_AsUnicode(nameobj); - if (!name) - return NULL; - - hMod = LoadLibraryW(name); - if (!hMod) - return PyErr_SetFromWindowsErr(GetLastError()); + WCHAR *name; + PyObject *nameobj; + PyObject *ignored; + HMODULE hMod; + if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored)) + return NULL; + + name = PyUnicode_AsUnicode(nameobj); + if (!name) + return NULL; + + hMod = LoadLibraryW(name); + if (!hMod) + return PyErr_SetFromWindowsErr(GetLastError()); #ifdef _WIN64 - return PyLong_FromVoidPtr(hMod); + return PyLong_FromVoidPtr(hMod); #else - return Py_BuildValue("i", hMod); + return Py_BuildValue("i", hMod); #endif } @@ -1271,13 +1271,13 @@ static char free_library_doc[] = Free the handle of an executable previously loaded by LoadLibrary.\n"; static PyObject *free_library(PyObject *self, PyObject *args) { - void *hMod; - if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod)) - return NULL; - if (!FreeLibrary((HMODULE)hMod)) - return PyErr_SetFromWindowsErr(GetLastError()); - Py_INCREF(Py_None); - return Py_None; + void *hMod; + if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod)) + return NULL; + if (!FreeLibrary((HMODULE)hMod)) + return PyErr_SetFromWindowsErr(GetLastError()); + Py_INCREF(Py_None); + return Py_None; } /* obsolete, should be removed */ @@ -1285,55 +1285,55 @@ static PyObject *free_library(PyObject *self, PyObject *args) static PyObject * call_commethod(PyObject *self, PyObject *args) { - IUnknown *pIunk; - int index; - PyObject *arguments; - PPROC *lpVtbl; - PyObject *result; - CDataObject *pcom; - PyObject *argtypes = NULL; - - if (!PyArg_ParseTuple(args, - "OiO!|O!", - &pcom, &index, - &PyTuple_Type, &arguments, - &PyTuple_Type, &argtypes)) - return NULL; - - if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) { - PyErr_Format(PyExc_TypeError, - "Method takes %d arguments (%d given)", - PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments)); - return NULL; - } - - if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) { - PyErr_Format(PyExc_TypeError, - "COM Pointer expected instead of %s instance", - Py_TYPE(pcom)->tp_name); - return NULL; - } - - if ((*(void **)(pcom->b_ptr)) == NULL) { - PyErr_SetString(PyExc_ValueError, - "The COM 'this' pointer is NULL"); - return NULL; - } - - pIunk = (IUnknown *)(*(void **)(pcom->b_ptr)); - lpVtbl = (PPROC *)(pIunk->lpVtbl); - - result = _ctypes_callproc(lpVtbl[index], - arguments, + IUnknown *pIunk; + int index; + PyObject *arguments; + PPROC *lpVtbl; + PyObject *result; + CDataObject *pcom; + PyObject *argtypes = NULL; + + if (!PyArg_ParseTuple(args, + "OiO!|O!", + &pcom, &index, + &PyTuple_Type, &arguments, + &PyTuple_Type, &argtypes)) + return NULL; + + if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) { + PyErr_Format(PyExc_TypeError, + "Method takes %d arguments (%d given)", + PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments)); + return NULL; + } + + if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) { + PyErr_Format(PyExc_TypeError, + "COM Pointer expected instead of %s instance", + Py_TYPE(pcom)->tp_name); + return NULL; + } + + if ((*(void **)(pcom->b_ptr)) == NULL) { + PyErr_SetString(PyExc_ValueError, + "The COM 'this' pointer is NULL"); + return NULL; + } + + pIunk = (IUnknown *)(*(void **)(pcom->b_ptr)); + lpVtbl = (PPROC *)(pIunk->lpVtbl); + + result = _ctypes_callproc(lpVtbl[index], + arguments, #ifdef MS_WIN32 - pIunk, - NULL, + pIunk, + NULL, #endif - FUNCFLAG_HRESULT, /* flags */ - argtypes, /* self->argtypes */ - NULL, /* self->restype */ - NULL); /* checker */ - return result; + FUNCFLAG_HRESULT, /* flags */ + argtypes, /* self->argtypes */ + NULL, /* self->restype */ + NULL); /* checker */ + return result; } static char copy_com_pointer_doc[] = @@ -1342,102 +1342,102 @@ static char copy_com_pointer_doc[] = static PyObject * copy_com_pointer(PyObject *self, PyObject *args) { - PyObject *p1, *p2, *r = NULL; - struct argument a, b; - IUnknown *src, **pdst; - if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2)) - return NULL; - a.keep = b.keep = NULL; - - if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b)) - goto done; - src = (IUnknown *)a.value.p; - pdst = (IUnknown **)b.value.p; - - if (pdst == NULL) - r = PyLong_FromLong(E_POINTER); - else { - if (src) - src->lpVtbl->AddRef(src); - *pdst = src; - r = PyLong_FromLong(S_OK); - } + PyObject *p1, *p2, *r = NULL; + struct argument a, b; + IUnknown *src, **pdst; + if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2)) + return NULL; + a.keep = b.keep = NULL; + + if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b)) + goto done; + src = (IUnknown *)a.value.p; + pdst = (IUnknown **)b.value.p; + + if (pdst == NULL) + r = PyLong_FromLong(E_POINTER); + else { + if (src) + src->lpVtbl->AddRef(src); + *pdst = src; + r = PyLong_FromLong(S_OK); + } done: - Py_XDECREF(a.keep); - Py_XDECREF(b.keep); - return r; + Py_XDECREF(a.keep); + Py_XDECREF(b.keep); + return r; } #else static PyObject *py_dl_open(PyObject *self, PyObject *args) { - PyObject *name, *name2; - char *name_str; - void * handle; -#ifdef RTLD_LOCAL - int mode = RTLD_NOW | RTLD_LOCAL; + PyObject *name, *name2; + char *name_str; + void * handle; +#ifdef RTLD_LOCAL + int mode = RTLD_NOW | RTLD_LOCAL; #else - /* cygwin doesn't define RTLD_LOCAL */ - int mode = RTLD_NOW; + /* cygwin doesn't define RTLD_LOCAL */ + int mode = RTLD_NOW; #endif - if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode)) - return NULL; - mode |= RTLD_NOW; - if (name != Py_None) { - if (PyUnicode_FSConverter(name, &name2) == 0) - return NULL; - if (PyBytes_Check(name2)) - name_str = PyBytes_AS_STRING(name2); - else - name_str = PyByteArray_AS_STRING(name2); - } else { - name_str = NULL; - name2 = NULL; - } - handle = ctypes_dlopen(name_str, mode); - Py_XDECREF(name2); - if (!handle) { - char *errmsg = ctypes_dlerror(); - if (!errmsg) - errmsg = "dlopen() error"; - PyErr_SetString(PyExc_OSError, - errmsg); - return NULL; - } - return PyLong_FromVoidPtr(handle); + if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode)) + return NULL; + mode |= RTLD_NOW; + if (name != Py_None) { + if (PyUnicode_FSConverter(name, &name2) == 0) + return NULL; + if (PyBytes_Check(name2)) + name_str = PyBytes_AS_STRING(name2); + else + name_str = PyByteArray_AS_STRING(name2); + } else { + name_str = NULL; + name2 = NULL; + } + handle = ctypes_dlopen(name_str, mode); + Py_XDECREF(name2); + if (!handle) { + char *errmsg = ctypes_dlerror(); + if (!errmsg) + errmsg = "dlopen() error"; + PyErr_SetString(PyExc_OSError, + errmsg); + return NULL; + } + return PyLong_FromVoidPtr(handle); } static PyObject *py_dl_close(PyObject *self, PyObject *args) { - void *handle; - - if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle)) - return NULL; - if (dlclose(handle)) { - PyErr_SetString(PyExc_OSError, - ctypes_dlerror()); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + void *handle; + + if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle)) + return NULL; + if (dlclose(handle)) { + PyErr_SetString(PyExc_OSError, + ctypes_dlerror()); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } static PyObject *py_dl_sym(PyObject *self, PyObject *args) { - char *name; - void *handle; - void *ptr; - - if (!PyArg_ParseTuple(args, "O&s:dlsym", - &_parse_voidp, &handle, &name)) - return NULL; - ptr = ctypes_dlsym((void*)handle, name); - if (!ptr) { - PyErr_SetString(PyExc_OSError, - ctypes_dlerror()); - return NULL; - } - return PyLong_FromVoidPtr(ptr); + char *name; + void *handle; + void *ptr; + + if (!PyArg_ParseTuple(args, "O&s:dlsym", + &_parse_voidp, &handle, &name)) + return NULL; + ptr = ctypes_dlsym((void*)handle, name); + if (!ptr) { + PyErr_SetString(PyExc_OSError, + ctypes_dlerror()); + return NULL; + } + return PyLong_FromVoidPtr(ptr); } #endif @@ -1449,27 +1449,27 @@ static PyObject *py_dl_sym(PyObject *self, PyObject *args) static PyObject * call_function(PyObject *self, PyObject *args) { - void *func; - PyObject *arguments; - PyObject *result; - - if (!PyArg_ParseTuple(args, - "O&O!", - &_parse_voidp, &func, - &PyTuple_Type, &arguments)) - return NULL; - - result = _ctypes_callproc((PPROC)func, - arguments, + void *func; + PyObject *arguments; + PyObject *result; + + if (!PyArg_ParseTuple(args, + "O&O!", + &_parse_voidp, &func, + &PyTuple_Type, &arguments)) + return NULL; + + result = _ctypes_callproc((PPROC)func, + arguments, #ifdef MS_WIN32 - NULL, - NULL, + NULL, + NULL, #endif - 0, /* flags */ - NULL, /* self->argtypes */ - NULL, /* self->restype */ - NULL); /* checker */ - return result; + 0, /* flags */ + NULL, /* self->argtypes */ + NULL, /* self->restype */ + NULL); /* checker */ + return result; } /* @@ -1480,27 +1480,27 @@ call_function(PyObject *self, PyObject *args) static PyObject * call_cdeclfunction(PyObject *self, PyObject *args) { - void *func; - PyObject *arguments; - PyObject *result; - - if (!PyArg_ParseTuple(args, - "O&O!", - &_parse_voidp, &func, - &PyTuple_Type, &arguments)) - return NULL; - - result = _ctypes_callproc((PPROC)func, - arguments, + void *func; + PyObject *arguments; + PyObject *result; + + if (!PyArg_ParseTuple(args, + "O&O!", + &_parse_voidp, &func, + &PyTuple_Type, &arguments)) + return NULL; + + result = _ctypes_callproc((PPROC)func, + arguments, #ifdef MS_WIN32 - NULL, - NULL, + NULL, + NULL, #endif - FUNCFLAG_CDECL, /* flags */ - NULL, /* self->argtypes */ - NULL, /* self->restype */ - NULL); /* checker */ - return result; + FUNCFLAG_CDECL, /* flags */ + NULL, /* self->argtypes */ + NULL, /* self->restype */ + NULL); /* checker */ + return result; } /***************************************************************** @@ -1514,17 +1514,17 @@ static char sizeof_doc[] = static PyObject * sizeof_func(PyObject *self, PyObject *obj) { - StgDictObject *dict; + StgDictObject *dict; - dict = PyType_stgdict(obj); - if (dict) - return PyLong_FromSsize_t(dict->size); + dict = PyType_stgdict(obj); + if (dict) + return PyLong_FromSsize_t(dict->size); - if (CDataObject_Check(obj)) - return PyLong_FromSsize_t(((CDataObject *)obj)->b_size); - PyErr_SetString(PyExc_TypeError, - "this type has no size"); - return NULL; + if (CDataObject_Check(obj)) + return PyLong_FromSsize_t(((CDataObject *)obj)->b_size); + PyErr_SetString(PyExc_TypeError, + "this type has no size"); + return NULL; } static char alignment_doc[] = @@ -1535,19 +1535,19 @@ static char alignment_doc[] = static PyObject * align_func(PyObject *self, PyObject *obj) { - StgDictObject *dict; + StgDictObject *dict; - dict = PyType_stgdict(obj); - if (dict) - return PyLong_FromSsize_t(dict->align); + dict = PyType_stgdict(obj); + if (dict) + return PyLong_FromSsize_t(dict->align); - dict = PyObject_stgdict(obj); - if (dict) - return PyLong_FromSsize_t(dict->align); + dict = PyObject_stgdict(obj); + if (dict) + return PyLong_FromSsize_t(dict->align); - PyErr_SetString(PyExc_TypeError, - "no alignment info"); - return NULL; + PyErr_SetString(PyExc_TypeError, + "no alignment info"); + return NULL; } static char byref_doc[] = @@ -1562,36 +1562,36 @@ static char byref_doc[] = static PyObject * byref(PyObject *self, PyObject *args) { - PyCArgObject *parg; - PyObject *obj; - PyObject *pyoffset = NULL; - Py_ssize_t offset = 0; - - if (!PyArg_UnpackTuple(args, "byref", 1, 2, - &obj, &pyoffset)) - return NULL; - if (pyoffset) { - offset = PyNumber_AsSsize_t(pyoffset, NULL); - if (offset == -1 && PyErr_Occurred()) - return NULL; - } - if (!CDataObject_Check(obj)) { - PyErr_Format(PyExc_TypeError, - "byref() argument must be a ctypes instance, not '%s'", - Py_TYPE(obj)->tp_name); - return NULL; - } - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - Py_INCREF(obj); - parg->obj = obj; - parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset; - return (PyObject *)parg; + PyCArgObject *parg; + PyObject *obj; + PyObject *pyoffset = NULL; + Py_ssize_t offset = 0; + + if (!PyArg_UnpackTuple(args, "byref", 1, 2, + &obj, &pyoffset)) + return NULL; + if (pyoffset) { + offset = PyNumber_AsSsize_t(pyoffset, NULL); + if (offset == -1 && PyErr_Occurred()) + return NULL; + } + if (!CDataObject_Check(obj)) { + PyErr_Format(PyExc_TypeError, + "byref() argument must be a ctypes instance, not '%s'", + Py_TYPE(obj)->tp_name); + return NULL; + } + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + Py_INCREF(obj); + parg->obj = obj; + parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset; + return (PyObject *)parg; } static char addressof_doc[] = @@ -1601,44 +1601,44 @@ static char addressof_doc[] = static PyObject * addressof(PyObject *self, PyObject *obj) { - if (CDataObject_Check(obj)) - return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr); - PyErr_SetString(PyExc_TypeError, - "invalid type"); - return NULL; + if (CDataObject_Check(obj)) + return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr); + PyErr_SetString(PyExc_TypeError, + "invalid type"); + return NULL; } static int converter(PyObject *obj, void **address) { - *address = PyLong_AsVoidPtr(obj); - return *address != NULL; + *address = PyLong_AsVoidPtr(obj); + return *address != NULL; } static PyObject * My_PyObj_FromPtr(PyObject *self, PyObject *args) { - PyObject *ob; - if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob)) - return NULL; - Py_INCREF(ob); - return ob; + PyObject *ob; + if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob)) + return NULL; + Py_INCREF(ob); + return ob; } static PyObject * My_Py_INCREF(PyObject *self, PyObject *arg) { - Py_INCREF(arg); /* that's what this function is for */ - Py_INCREF(arg); /* that for returning it */ - return arg; + Py_INCREF(arg); /* that's what this function is for */ + Py_INCREF(arg); /* that for returning it */ + return arg; } static PyObject * My_Py_DECREF(PyObject *self, PyObject *arg) { - Py_DECREF(arg); /* that's what this function is for */ - Py_INCREF(arg); /* that's for returning it */ - return arg; + Py_DECREF(arg); /* that's what this function is for */ + Py_INCREF(arg); /* that's for returning it */ + return arg; } #ifdef CTYPES_UNICODE @@ -1652,234 +1652,234 @@ between unicode and strings. Returns the previous values.\n"; static PyObject * set_conversion_mode(PyObject *self, PyObject *args) { - char *coding, *mode; - PyObject *result; - - if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode)) - return NULL; - result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors); - if (coding) { - PyMem_Free(_ctypes_conversion_encoding); - _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1); - strcpy(_ctypes_conversion_encoding, coding); - } else { - _ctypes_conversion_encoding = NULL; - } - PyMem_Free(_ctypes_conversion_errors); - _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1); - strcpy(_ctypes_conversion_errors, mode); - return result; + char *coding, *mode; + PyObject *result; + + if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode)) + return NULL; + result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors); + if (coding) { + PyMem_Free(_ctypes_conversion_encoding); + _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1); + strcpy(_ctypes_conversion_encoding, coding); + } else { + _ctypes_conversion_encoding = NULL; + } + PyMem_Free(_ctypes_conversion_errors); + _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1); + strcpy(_ctypes_conversion_errors, mode); + return result; } #endif static PyObject * resize(PyObject *self, PyObject *args) { - CDataObject *obj; - StgDictObject *dict; - Py_ssize_t size; - - if (!PyArg_ParseTuple(args, - "On:resize", - &obj, &size)) - return NULL; - - dict = PyObject_stgdict((PyObject *)obj); - if (dict == NULL) { - PyErr_SetString(PyExc_TypeError, - "excepted ctypes instance"); - return NULL; - } - if (size < dict->size) { - PyErr_Format(PyExc_ValueError, - "minimum size is %zd", - dict->size); - return NULL; - } - if (obj->b_needsfree == 0) { - PyErr_Format(PyExc_ValueError, - "Memory cannot be resized because this object doesn't own it"); - return NULL; - } - if (size <= sizeof(obj->b_value)) { - /* internal default buffer is large enough */ - obj->b_size = size; - goto done; - } - if (obj->b_size <= sizeof(obj->b_value)) { - /* We are currently using the objects default buffer, but it - isn't large enough any more. */ - void *ptr = PyMem_Malloc(size); - if (ptr == NULL) - return PyErr_NoMemory(); - memset(ptr, 0, size); - memmove(ptr, obj->b_ptr, obj->b_size); - obj->b_ptr = ptr; - obj->b_size = size; - } else { - void * ptr = PyMem_Realloc(obj->b_ptr, size); - if (ptr == NULL) - return PyErr_NoMemory(); - obj->b_ptr = ptr; - obj->b_size = size; - } + CDataObject *obj; + StgDictObject *dict; + Py_ssize_t size; + + if (!PyArg_ParseTuple(args, + "On:resize", + &obj, &size)) + return NULL; + + dict = PyObject_stgdict((PyObject *)obj); + if (dict == NULL) { + PyErr_SetString(PyExc_TypeError, + "excepted ctypes instance"); + return NULL; + } + if (size < dict->size) { + PyErr_Format(PyExc_ValueError, + "minimum size is %zd", + dict->size); + return NULL; + } + if (obj->b_needsfree == 0) { + PyErr_Format(PyExc_ValueError, + "Memory cannot be resized because this object doesn't own it"); + return NULL; + } + if (size <= sizeof(obj->b_value)) { + /* internal default buffer is large enough */ + obj->b_size = size; + goto done; + } + if (obj->b_size <= sizeof(obj->b_value)) { + /* We are currently using the objects default buffer, but it + isn't large enough any more. */ + void *ptr = PyMem_Malloc(size); + if (ptr == NULL) + return PyErr_NoMemory(); + memset(ptr, 0, size); + memmove(ptr, obj->b_ptr, obj->b_size); + obj->b_ptr = ptr; + obj->b_size = size; + } else { + void * ptr = PyMem_Realloc(obj->b_ptr, size); + if (ptr == NULL) + return PyErr_NoMemory(); + obj->b_ptr = ptr; + obj->b_size = size; + } done: - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * unpickle(PyObject *self, PyObject *args) { - PyObject *typ; - PyObject *state; - PyObject *result; - PyObject *tmp; - - if (!PyArg_ParseTuple(args, "OO", &typ, &state)) - return NULL; - result = PyObject_CallMethod(typ, "__new__", "O", typ); - if (result == NULL) - return NULL; - tmp = PyObject_CallMethod(result, "__setstate__", "O", state); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } - Py_DECREF(tmp); - return result; + PyObject *typ; + PyObject *state; + PyObject *result; + PyObject *tmp; + + if (!PyArg_ParseTuple(args, "OO", &typ, &state)) + return NULL; + result = PyObject_CallMethod(typ, "__new__", "O", typ); + if (result == NULL) + return NULL; + tmp = PyObject_CallMethod(result, "__setstate__", "O", state); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } + Py_DECREF(tmp); + return result; } static PyObject * POINTER(PyObject *self, PyObject *cls) { - PyObject *result; - PyTypeObject *typ; - PyObject *key; - char *buf; - - result = PyDict_GetItem(_ctypes_ptrtype_cache, cls); - if (result) { - Py_INCREF(result); - return result; - } - if (PyUnicode_CheckExact(cls)) { - char *name = _PyUnicode_AsString(cls); - buf = alloca(strlen(name) + 3 + 1); - sprintf(buf, "LP_%s", name); - result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), - "s(O){}", - buf, - &PyCPointer_Type); - if (result == NULL) - return result; - key = PyLong_FromVoidPtr(result); - } else if (PyType_Check(cls)) { - typ = (PyTypeObject *)cls; - buf = alloca(strlen(typ->tp_name) + 3 + 1); - sprintf(buf, "LP_%s", typ->tp_name); - result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), - "s(O){sO}", - buf, - &PyCPointer_Type, - "_type_", cls); - if (result == NULL) - return result; - Py_INCREF(cls); - key = cls; - } else { - PyErr_SetString(PyExc_TypeError, "must be a ctypes type"); - return NULL; - } - if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) { - Py_DECREF(result); - Py_DECREF(key); - return NULL; - } - Py_DECREF(key); - return result; + PyObject *result; + PyTypeObject *typ; + PyObject *key; + char *buf; + + result = PyDict_GetItem(_ctypes_ptrtype_cache, cls); + if (result) { + Py_INCREF(result); + return result; + } + if (PyUnicode_CheckExact(cls)) { + char *name = _PyUnicode_AsString(cls); + buf = alloca(strlen(name) + 3 + 1); + sprintf(buf, "LP_%s", name); + result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), + "s(O){}", + buf, + &PyCPointer_Type); + if (result == NULL) + return result; + key = PyLong_FromVoidPtr(result); + } else if (PyType_Check(cls)) { + typ = (PyTypeObject *)cls; + buf = alloca(strlen(typ->tp_name) + 3 + 1); + sprintf(buf, "LP_%s", typ->tp_name); + result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), + "s(O){sO}", + buf, + &PyCPointer_Type, + "_type_", cls); + if (result == NULL) + return result; + Py_INCREF(cls); + key = cls; + } else { + PyErr_SetString(PyExc_TypeError, "must be a ctypes type"); + return NULL; + } + if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) { + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + Py_DECREF(key); + return result; } static PyObject * pointer(PyObject *self, PyObject *arg) { - PyObject *result; - PyObject *typ; - - typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg)); - if (typ) - return PyObject_CallFunctionObjArgs(typ, arg, NULL); - typ = POINTER(NULL, (PyObject *)Py_TYPE(arg)); - if (typ == NULL) - return NULL; - result = PyObject_CallFunctionObjArgs(typ, arg, NULL); - Py_DECREF(typ); - return result; + PyObject *result; + PyObject *typ; + + typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg)); + if (typ) + return PyObject_CallFunctionObjArgs(typ, arg, NULL); + typ = POINTER(NULL, (PyObject *)Py_TYPE(arg)); + if (typ == NULL) + return NULL; + result = PyObject_CallFunctionObjArgs(typ, arg, NULL); + Py_DECREF(typ); + return result; } static PyObject * buffer_info(PyObject *self, PyObject *arg) { - StgDictObject *dict = PyType_stgdict(arg); - PyObject *shape; - Py_ssize_t i; - - if (dict == NULL) - dict = PyObject_stgdict(arg); - if (dict == NULL) { - PyErr_SetString(PyExc_TypeError, - "not a ctypes type or object"); - return NULL; - } - shape = PyTuple_New(dict->ndim); - if (shape == NULL) - return NULL; - for (i = 0; i < (int)dict->ndim; ++i) - PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i])); - - if (PyErr_Occurred()) { - Py_DECREF(shape); - return NULL; - } - return Py_BuildValue("siN", dict->format, dict->ndim, shape); + StgDictObject *dict = PyType_stgdict(arg); + PyObject *shape; + Py_ssize_t i; + + if (dict == NULL) + dict = PyObject_stgdict(arg); + if (dict == NULL) { + PyErr_SetString(PyExc_TypeError, + "not a ctypes type or object"); + return NULL; + } + shape = PyTuple_New(dict->ndim); + if (shape == NULL) + return NULL; + for (i = 0; i < (int)dict->ndim; ++i) + PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i])); + + if (PyErr_Occurred()) { + Py_DECREF(shape); + return NULL; + } + return Py_BuildValue("siN", dict->format, dict->ndim, shape); } PyMethodDef _ctypes_module_methods[] = { - {"get_errno", get_errno, METH_NOARGS}, - {"set_errno", set_errno, METH_VARARGS}, - {"POINTER", POINTER, METH_O }, - {"pointer", pointer, METH_O }, - {"_unpickle", unpickle, METH_VARARGS }, - {"buffer_info", buffer_info, METH_O, "Return buffer interface information"}, - {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"}, + {"get_errno", get_errno, METH_NOARGS}, + {"set_errno", set_errno, METH_VARARGS}, + {"POINTER", POINTER, METH_O }, + {"pointer", pointer, METH_O }, + {"_unpickle", unpickle, METH_VARARGS }, + {"buffer_info", buffer_info, METH_O, "Return buffer interface information"}, + {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"}, #ifdef CTYPES_UNICODE - {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc}, + {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc}, #endif #ifdef MS_WIN32 - {"get_last_error", get_last_error, METH_NOARGS}, - {"set_last_error", set_last_error, METH_VARARGS}, - {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc}, - {"FormatError", format_error, METH_VARARGS, format_error_doc}, - {"LoadLibrary", load_library, METH_VARARGS, load_library_doc}, - {"FreeLibrary", free_library, METH_VARARGS, free_library_doc}, - {"call_commethod", call_commethod, METH_VARARGS }, - {"_check_HRESULT", check_hresult, METH_VARARGS}, + {"get_last_error", get_last_error, METH_NOARGS}, + {"set_last_error", set_last_error, METH_VARARGS}, + {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc}, + {"FormatError", format_error, METH_VARARGS, format_error_doc}, + {"LoadLibrary", load_library, METH_VARARGS, load_library_doc}, + {"FreeLibrary", free_library, METH_VARARGS, free_library_doc}, + {"call_commethod", call_commethod, METH_VARARGS }, + {"_check_HRESULT", check_hresult, METH_VARARGS}, #else - {"dlopen", py_dl_open, METH_VARARGS, - "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"}, - {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"}, - {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"}, + {"dlopen", py_dl_open, METH_VARARGS, + "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"}, + {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"}, + {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"}, #endif - {"alignment", align_func, METH_O, alignment_doc}, - {"sizeof", sizeof_func, METH_O, sizeof_doc}, - {"byref", byref, METH_VARARGS, byref_doc}, - {"addressof", addressof, METH_O, addressof_doc}, - {"call_function", call_function, METH_VARARGS }, - {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS }, - {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS }, - {"Py_INCREF", My_Py_INCREF, METH_O }, - {"Py_DECREF", My_Py_DECREF, METH_O }, - {NULL, NULL} /* Sentinel */ + {"alignment", align_func, METH_O, alignment_doc}, + {"sizeof", sizeof_func, METH_O, sizeof_doc}, + {"byref", byref, METH_VARARGS, byref_doc}, + {"addressof", addressof, METH_O, addressof_doc}, + {"call_function", call_function, METH_VARARGS }, + {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS }, + {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS }, + {"Py_INCREF", My_Py_INCREF, METH_O }, + {"Py_DECREF", My_Py_DECREF, METH_O }, + {NULL, NULL} /* Sentinel */ }; /* diff --git a/Modules/_ctypes/cfield.c b/Modules/_ctypes/cfield.c index f7fd7fa..441ed9e 100644 --- a/Modules/_ctypes/cfield.c +++ b/Modules/_ctypes/cfield.c @@ -11,10 +11,10 @@ static void pymem_destructor(PyObject *ptr) { - void *p = PyCapsule_GetPointer(ptr, CTYPES_CFIELD_CAPSULE_NAME_PYMEM); - if (p) { - PyMem_Free(p); - } + void *p = PyCapsule_GetPointer(ptr, CTYPES_CFIELD_CAPSULE_NAME_PYMEM); + if (p) { + PyMem_Free(p); + } } @@ -25,9 +25,9 @@ static void pymem_destructor(PyObject *ptr) static PyObject * PyCField_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - CFieldObject *obj; - obj = (CFieldObject *)type->tp_alloc(type, 0); - return (PyObject *)obj; + CFieldObject *obj; + obj = (CFieldObject *)type->tp_alloc(type, 0); + return (PyObject *)obj; } /* @@ -44,297 +44,297 @@ PyCField_new(PyTypeObject *type, PyObject *args, PyObject *kwds) */ PyObject * PyCField_FromDesc(PyObject *desc, Py_ssize_t index, - Py_ssize_t *pfield_size, int bitsize, int *pbitofs, - Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, - int pack, int big_endian) -{ - CFieldObject *self; - PyObject *proto; - Py_ssize_t size, align, length; - SETFUNC setfunc = NULL; - GETFUNC getfunc = NULL; - StgDictObject *dict; - int fieldtype; + Py_ssize_t *pfield_size, int bitsize, int *pbitofs, + Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, + int pack, int big_endian) +{ + CFieldObject *self; + PyObject *proto; + Py_ssize_t size, align, length; + SETFUNC setfunc = NULL; + GETFUNC getfunc = NULL; + StgDictObject *dict; + int fieldtype; #define NO_BITFIELD 0 #define NEW_BITFIELD 1 #define CONT_BITFIELD 2 #define EXPAND_BITFIELD 3 - self = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, - NULL); - if (self == NULL) - return NULL; - dict = PyType_stgdict(desc); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "has no _stginfo_"); - Py_DECREF(self); - return NULL; - } - if (bitsize /* this is a bitfield request */ - && *pfield_size /* we have a bitfield open */ + self = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, + NULL); + if (self == NULL) + return NULL; + dict = PyType_stgdict(desc); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "has no _stginfo_"); + Py_DECREF(self); + return NULL; + } + if (bitsize /* this is a bitfield request */ + && *pfield_size /* we have a bitfield open */ #ifdef MS_WIN32 - /* MSVC, GCC with -mms-bitfields */ - && dict->size * 8 == *pfield_size + /* MSVC, GCC with -mms-bitfields */ + && dict->size * 8 == *pfield_size #else - /* GCC */ - && dict->size * 8 <= *pfield_size + /* GCC */ + && dict->size * 8 <= *pfield_size #endif - && (*pbitofs + bitsize) <= *pfield_size) { - /* continue bit field */ - fieldtype = CONT_BITFIELD; + && (*pbitofs + bitsize) <= *pfield_size) { + /* continue bit field */ + fieldtype = CONT_BITFIELD; #ifndef MS_WIN32 - } else if (bitsize /* this is a bitfield request */ - && *pfield_size /* we have a bitfield open */ - && dict->size * 8 >= *pfield_size - && (*pbitofs + bitsize) <= dict->size * 8) { - /* expand bit field */ - fieldtype = EXPAND_BITFIELD; + } else if (bitsize /* this is a bitfield request */ + && *pfield_size /* we have a bitfield open */ + && dict->size * 8 >= *pfield_size + && (*pbitofs + bitsize) <= dict->size * 8) { + /* expand bit field */ + fieldtype = EXPAND_BITFIELD; #endif - } else if (bitsize) { - /* start new bitfield */ - fieldtype = NEW_BITFIELD; - *pbitofs = 0; - *pfield_size = dict->size * 8; - } else { - /* not a bit field */ - fieldtype = NO_BITFIELD; - *pbitofs = 0; - *pfield_size = 0; - } - - size = dict->size; - length = dict->length; - proto = desc; - - /* Field descriptors for 'c_char * n' are be scpecial cased to - return a Python string instead of an Array object instance... - */ - if (PyCArrayTypeObject_Check(proto)) { - StgDictObject *adict = PyType_stgdict(proto); - StgDictObject *idict; - if (adict && adict->proto) { - idict = PyType_stgdict(adict->proto); - if (!idict) { - PyErr_SetString(PyExc_TypeError, - "has no _stginfo_"); - Py_DECREF(self); - return NULL; - } - if (idict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - struct fielddesc *fd = _ctypes_get_fielddesc("s"); - getfunc = fd->getfunc; - setfunc = fd->setfunc; - } + } else if (bitsize) { + /* start new bitfield */ + fieldtype = NEW_BITFIELD; + *pbitofs = 0; + *pfield_size = dict->size * 8; + } else { + /* not a bit field */ + fieldtype = NO_BITFIELD; + *pbitofs = 0; + *pfield_size = 0; + } + + size = dict->size; + length = dict->length; + proto = desc; + + /* Field descriptors for 'c_char * n' are be scpecial cased to + return a Python string instead of an Array object instance... + */ + if (PyCArrayTypeObject_Check(proto)) { + StgDictObject *adict = PyType_stgdict(proto); + StgDictObject *idict; + if (adict && adict->proto) { + idict = PyType_stgdict(adict->proto); + if (!idict) { + PyErr_SetString(PyExc_TypeError, + "has no _stginfo_"); + Py_DECREF(self); + return NULL; + } + if (idict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + struct fielddesc *fd = _ctypes_get_fielddesc("s"); + getfunc = fd->getfunc; + setfunc = fd->setfunc; + } #ifdef CTYPES_UNICODE - if (idict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - struct fielddesc *fd = _ctypes_get_fielddesc("U"); - getfunc = fd->getfunc; - setfunc = fd->setfunc; - } + if (idict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + struct fielddesc *fd = _ctypes_get_fielddesc("U"); + getfunc = fd->getfunc; + setfunc = fd->setfunc; + } #endif - } - } - - self->setfunc = setfunc; - self->getfunc = getfunc; - self->index = index; - - Py_INCREF(proto); - self->proto = proto; - - switch (fieldtype) { - case NEW_BITFIELD: - if (big_endian) - self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; - else - self->size = (bitsize << 16) + *pbitofs; - *pbitofs = bitsize; - /* fall through */ - case NO_BITFIELD: - if (pack) - align = min(pack, dict->align); - else - align = dict->align; - if (align && *poffset % align) { - Py_ssize_t delta = align - (*poffset % align); - *psize += delta; - *poffset += delta; - } - - if (bitsize == 0) - self->size = size; - *psize += size; - - self->offset = *poffset; - *poffset += size; - - *palign = align; - break; - - case EXPAND_BITFIELD: - *poffset += dict->size - *pfield_size/8; - *psize += dict->size - *pfield_size/8; - - *pfield_size = dict->size * 8; - - if (big_endian) - self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; - else - self->size = (bitsize << 16) + *pbitofs; - - self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ - *pbitofs += bitsize; - break; - - case CONT_BITFIELD: - if (big_endian) - self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; - else - self->size = (bitsize << 16) + *pbitofs; - - self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ - *pbitofs += bitsize; - break; - } - - return (PyObject *)self; + } + } + + self->setfunc = setfunc; + self->getfunc = getfunc; + self->index = index; + + Py_INCREF(proto); + self->proto = proto; + + switch (fieldtype) { + case NEW_BITFIELD: + if (big_endian) + self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; + else + self->size = (bitsize << 16) + *pbitofs; + *pbitofs = bitsize; + /* fall through */ + case NO_BITFIELD: + if (pack) + align = min(pack, dict->align); + else + align = dict->align; + if (align && *poffset % align) { + Py_ssize_t delta = align - (*poffset % align); + *psize += delta; + *poffset += delta; + } + + if (bitsize == 0) + self->size = size; + *psize += size; + + self->offset = *poffset; + *poffset += size; + + *palign = align; + break; + + case EXPAND_BITFIELD: + *poffset += dict->size - *pfield_size/8; + *psize += dict->size - *pfield_size/8; + + *pfield_size = dict->size * 8; + + if (big_endian) + self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; + else + self->size = (bitsize << 16) + *pbitofs; + + self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ + *pbitofs += bitsize; + break; + + case CONT_BITFIELD: + if (big_endian) + self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; + else + self->size = (bitsize << 16) + *pbitofs; + + self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ + *pbitofs += bitsize; + break; + } + + return (PyObject *)self; } static int PyCField_set(CFieldObject *self, PyObject *inst, PyObject *value) { - CDataObject *dst; - char *ptr; - assert(CDataObject_Check(inst)); - dst = (CDataObject *)inst; - ptr = dst->b_ptr + self->offset; - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - return PyCData_set(inst, self->proto, self->setfunc, value, - self->index, self->size, ptr); + CDataObject *dst; + char *ptr; + assert(CDataObject_Check(inst)); + dst = (CDataObject *)inst; + ptr = dst->b_ptr + self->offset; + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } + return PyCData_set(inst, self->proto, self->setfunc, value, + self->index, self->size, ptr); } static PyObject * PyCField_get(CFieldObject *self, PyObject *inst, PyTypeObject *type) { - CDataObject *src; - if (inst == NULL) { - Py_INCREF(self); - return (PyObject *)self; - } - assert(CDataObject_Check(inst)); - src = (CDataObject *)inst; - return PyCData_get(self->proto, self->getfunc, inst, - self->index, self->size, src->b_ptr + self->offset); + CDataObject *src; + if (inst == NULL) { + Py_INCREF(self); + return (PyObject *)self; + } + assert(CDataObject_Check(inst)); + src = (CDataObject *)inst; + return PyCData_get(self->proto, self->getfunc, inst, + self->index, self->size, src->b_ptr + self->offset); } static PyObject * PyCField_get_offset(PyObject *self, void *data) { - return PyLong_FromSsize_t(((CFieldObject *)self)->offset); + return PyLong_FromSsize_t(((CFieldObject *)self)->offset); } static PyObject * PyCField_get_size(PyObject *self, void *data) { - return PyLong_FromSsize_t(((CFieldObject *)self)->size); + return PyLong_FromSsize_t(((CFieldObject *)self)->size); } static PyGetSetDef PyCField_getset[] = { - { "offset", PyCField_get_offset, NULL, "offset in bytes of this field" }, - { "size", PyCField_get_size, NULL, "size in bytes of this field" }, - { NULL, NULL, NULL, NULL }, + { "offset", PyCField_get_offset, NULL, "offset in bytes of this field" }, + { "size", PyCField_get_size, NULL, "size in bytes of this field" }, + { NULL, NULL, NULL, NULL }, }; static int PyCField_traverse(CFieldObject *self, visitproc visit, void *arg) { - Py_VISIT(self->proto); - return 0; + Py_VISIT(self->proto); + return 0; } static int PyCField_clear(CFieldObject *self) { - Py_CLEAR(self->proto); - return 0; + Py_CLEAR(self->proto); + return 0; } static void PyCField_dealloc(PyObject *self) { - PyCField_clear((CFieldObject *)self); - self->ob_type->tp_free((PyObject *)self); + PyCField_clear((CFieldObject *)self); + self->ob_type->tp_free((PyObject *)self); } static PyObject * PyCField_repr(CFieldObject *self) { - PyObject *result; - Py_ssize_t bits = self->size >> 16; - Py_ssize_t size = self->size & 0xFFFF; - const char *name; + PyObject *result; + Py_ssize_t bits = self->size >> 16; + Py_ssize_t size = self->size & 0xFFFF; + const char *name; - name = ((PyTypeObject *)self->proto)->tp_name; + name = ((PyTypeObject *)self->proto)->tp_name; - if (bits) - result = PyUnicode_FromFormat( - "<Field type=%s, ofs=%zd:%zd, bits=%zd>", - name, self->offset, size, bits); - else - result = PyUnicode_FromFormat( - "<Field type=%s, ofs=%zd, size=%zd>", - name, self->offset, size); - return result; + if (bits) + result = PyUnicode_FromFormat( + "<Field type=%s, ofs=%zd:%zd, bits=%zd>", + name, self->offset, size, bits); + else + result = PyUnicode_FromFormat( + "<Field type=%s, ofs=%zd, size=%zd>", + name, self->offset, size); + return result; } PyTypeObject PyCField_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.CField", /* tp_name */ - sizeof(CFieldObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - PyCField_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)PyCField_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "Structure/Union member", /* tp_doc */ - (traverseproc)PyCField_traverse, /* tp_traverse */ - (inquiry)PyCField_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - PyCField_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)PyCField_get, /* tp_descr_get */ - (descrsetfunc)PyCField_set, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCField_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.CField", /* tp_name */ + sizeof(CFieldObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + PyCField_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)PyCField_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "Structure/Union member", /* tp_doc */ + (traverseproc)PyCField_traverse, /* tp_traverse */ + (inquiry)PyCField_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + PyCField_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)PyCField_get, /* tp_descr_get */ + (descrsetfunc)PyCField_set, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCField_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* Accessor functions @@ -347,18 +347,18 @@ PyTypeObject PyCField_Type = { static int get_long(PyObject *v, long *p) { - long x; + long x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongMask(v); - if (x == -1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongMask(v); + if (x == -1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } /* Same, but handling unsigned long */ @@ -366,18 +366,18 @@ get_long(PyObject *v, long *p) static int get_ulong(PyObject *v, unsigned long *p) { - unsigned long x; + unsigned long x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongMask(v); - if (x == (unsigned long)-1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongMask(v); + if (x == (unsigned long)-1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } #ifdef HAVE_LONG_LONG @@ -387,17 +387,17 @@ get_ulong(PyObject *v, unsigned long *p) static int get_longlong(PyObject *v, PY_LONG_LONG *p) { - PY_LONG_LONG x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongLongMask(v); - if (x == -1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + PY_LONG_LONG x; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongLongMask(v); + if (x == -1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } /* Same, but handling native unsigned long long. */ @@ -405,17 +405,17 @@ get_longlong(PyObject *v, PY_LONG_LONG *p) static int get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p) { - unsigned PY_LONG_LONG x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongLongMask(v); - if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + unsigned PY_LONG_LONG x; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongLongMask(v); + if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } #endif @@ -438,49 +438,49 @@ get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p) /* This macro CHANGES the first parameter IN PLACE. For proper sign handling, we must first shift left, then right. */ -#define GET_BITFIELD(v, size) \ - if (NUM_BITS(size)) { \ - v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \ - v >>= (sizeof(v)*8 - NUM_BITS(size)); \ - } +#define GET_BITFIELD(v, size) \ + if (NUM_BITS(size)) { \ + v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \ + v >>= (sizeof(v)*8 - NUM_BITS(size)); \ + } /* This macro RETURNS the first parameter with the bit field CHANGED. */ -#define SET(x, v, size) \ - (NUM_BITS(size) ? \ - ( ( x & ~(BIT_MASK(size) << LOW_BIT(size)) ) | ( (v & BIT_MASK(size)) << LOW_BIT(size) ) ) \ - : v) +#define SET(x, v, size) \ + (NUM_BITS(size) ? \ + ( ( x & ~(BIT_MASK(size) << LOW_BIT(size)) ) | ( (v & BIT_MASK(size)) << LOW_BIT(size) ) ) \ + : v) /* byte swapping macros */ -#define SWAP_2(v) \ - ( ( (v >> 8) & 0x00FF) | \ - ( (v << 8) & 0xFF00) ) +#define SWAP_2(v) \ + ( ( (v >> 8) & 0x00FF) | \ + ( (v << 8) & 0xFF00) ) -#define SWAP_4(v) \ - ( ( (v & 0x000000FF) << 24 ) | \ - ( (v & 0x0000FF00) << 8 ) | \ - ( (v & 0x00FF0000) >> 8 ) | \ - ( ((v >> 24) & 0xFF)) ) +#define SWAP_4(v) \ + ( ( (v & 0x000000FF) << 24 ) | \ + ( (v & 0x0000FF00) << 8 ) | \ + ( (v & 0x00FF0000) >> 8 ) | \ + ( ((v >> 24) & 0xFF)) ) #ifdef _MSC_VER -#define SWAP_8(v) \ - ( ( (v & 0x00000000000000FFL) << 56 ) | \ - ( (v & 0x000000000000FF00L) << 40 ) | \ - ( (v & 0x0000000000FF0000L) << 24 ) | \ - ( (v & 0x00000000FF000000L) << 8 ) | \ - ( (v & 0x000000FF00000000L) >> 8 ) | \ - ( (v & 0x0000FF0000000000L) >> 24 ) | \ - ( (v & 0x00FF000000000000L) >> 40 ) | \ - ( ((v >> 56) & 0xFF)) ) +#define SWAP_8(v) \ + ( ( (v & 0x00000000000000FFL) << 56 ) | \ + ( (v & 0x000000000000FF00L) << 40 ) | \ + ( (v & 0x0000000000FF0000L) << 24 ) | \ + ( (v & 0x00000000FF000000L) << 8 ) | \ + ( (v & 0x000000FF00000000L) >> 8 ) | \ + ( (v & 0x0000FF0000000000L) >> 24 ) | \ + ( (v & 0x00FF000000000000L) >> 40 ) | \ + ( ((v >> 56) & 0xFF)) ) #else -#define SWAP_8(v) \ - ( ( (v & 0x00000000000000FFLL) << 56 ) | \ - ( (v & 0x000000000000FF00LL) << 40 ) | \ - ( (v & 0x0000000000FF0000LL) << 24 ) | \ - ( (v & 0x00000000FF000000LL) << 8 ) | \ - ( (v & 0x000000FF00000000LL) >> 8 ) | \ - ( (v & 0x0000FF0000000000LL) >> 24 ) | \ - ( (v & 0x00FF000000000000LL) >> 40 ) | \ - ( ((v >> 56) & 0xFF)) ) +#define SWAP_8(v) \ + ( ( (v & 0x00000000000000FFLL) << 56 ) | \ + ( (v & 0x000000000000FF00LL) << 40 ) | \ + ( (v & 0x0000000000FF0000LL) << 24 ) | \ + ( (v & 0x00000000FF000000LL) << 8 ) | \ + ( (v & 0x000000FF00000000LL) >> 8 ) | \ + ( (v & 0x0000FF0000000000LL) >> 24 ) | \ + ( (v & 0x00FF000000000000LL) >> 40 ) | \ + ( ((v >> 56) & 0xFF)) ) #endif #define SWAP_INT SWAP_4 @@ -517,184 +517,184 @@ get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p) static PyObject * b_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - if (get_long(value, &val) < 0) - return NULL; - *(signed char *)ptr = (signed char)SET(*(signed char *)ptr, (signed char)val, size); - _RET(value); + long val; + if (get_long(value, &val) < 0) + return NULL; + *(signed char *)ptr = (signed char)SET(*(signed char *)ptr, (signed char)val, size); + _RET(value); } static PyObject * b_get(void *ptr, Py_ssize_t size) { - signed char val = *(signed char *)ptr; - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + signed char val = *(signed char *)ptr; + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * B_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - if (get_ulong(value, &val) < 0) - return NULL; - *(unsigned char *)ptr = (unsigned char)SET(*(unsigned char*)ptr, - (unsigned short)val, size); - _RET(value); + unsigned long val; + if (get_ulong(value, &val) < 0) + return NULL; + *(unsigned char *)ptr = (unsigned char)SET(*(unsigned char*)ptr, + (unsigned short)val, size); + _RET(value); } static PyObject * B_get(void *ptr, Py_ssize_t size) { - unsigned char val = *(unsigned char *)ptr; - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + unsigned char val = *(unsigned char *)ptr; + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * h_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - short x; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (short)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + long val; + short x; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (short)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * h_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - short field; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_2(field); - field = SET(field, (short)val, size); - field = SWAP_2(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + long val; + short field; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_2(field); + field = SET(field, (short)val, size); + field = SWAP_2(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * h_get(void *ptr, Py_ssize_t size) { - short val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong((long)val); + short val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong((long)val); } static PyObject * h_get_sw(void *ptr, Py_ssize_t size) { - short val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_2(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + short val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_2(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * H_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned short x; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (unsigned short)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned long val; + unsigned short x; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (unsigned short)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * H_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned short field; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_2(field); - field = SET(field, (unsigned short)val, size); - field = SWAP_2(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned long val; + unsigned short field; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_2(field); + field = SET(field, (unsigned short)val, size); + field = SWAP_2(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * H_get(void *ptr, Py_ssize_t size) { - unsigned short val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + unsigned short val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * H_get_sw(void *ptr, Py_ssize_t size) { - unsigned short val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_2(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + unsigned short val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_2(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * i_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - int x; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (int)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + long val; + int x; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (int)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * i_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - int field; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_INT(field); - field = SET(field, (int)val, size); - field = SWAP_INT(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + long val; + int field; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_INT(field); + field = SET(field, (int)val, size); + field = SWAP_INT(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * i_get(void *ptr, Py_ssize_t size) { - int val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + int val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * i_get_sw(void *ptr, Py_ssize_t size) { - int val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_INT(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + int val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_INT(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } #ifdef MS_WIN32 @@ -702,22 +702,22 @@ i_get_sw(void *ptr, Py_ssize_t size) static PyObject * vBOOL_set(void *ptr, PyObject *value, Py_ssize_t size) { - switch (PyObject_IsTrue(value)) { - case -1: - return NULL; - case 0: - *(short int *)ptr = VARIANT_FALSE; - _RET(value); - default: - *(short int *)ptr = VARIANT_TRUE; - _RET(value); - } + switch (PyObject_IsTrue(value)) { + case -1: + return NULL; + case 0: + *(short int *)ptr = VARIANT_FALSE; + _RET(value); + default: + *(short int *)ptr = VARIANT_TRUE; + _RET(value); + } } static PyObject * vBOOL_get(void *ptr, Py_ssize_t size) { - return PyBool_FromLong((long)*(short int *)ptr); + return PyBool_FromLong((long)*(short int *)ptr); } #endif @@ -732,260 +732,260 @@ vBOOL_get(void *ptr, Py_ssize_t size) static PyObject * bool_set(void *ptr, PyObject *value, Py_ssize_t size) { - switch (PyObject_IsTrue(value)) { - case -1: - return NULL; - case 0: - *(BOOL_TYPE *)ptr = 0; - _RET(value); - default: - *(BOOL_TYPE *)ptr = 1; - _RET(value); - } + switch (PyObject_IsTrue(value)) { + case -1: + return NULL; + case 0: + *(BOOL_TYPE *)ptr = 0; + _RET(value); + default: + *(BOOL_TYPE *)ptr = 1; + _RET(value); + } } static PyObject * bool_get(void *ptr, Py_ssize_t size) { - return PyBool_FromLong((long)*(BOOL_TYPE *)ptr); + return PyBool_FromLong((long)*(BOOL_TYPE *)ptr); } static PyObject * I_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned int x; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (unsigned int)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned long val; + unsigned int x; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (unsigned int)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * I_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned int field; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = (unsigned int)SET(field, (unsigned int)val, size); - field = SWAP_INT(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned long val; + unsigned int field; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = (unsigned int)SET(field, (unsigned int)val, size); + field = SWAP_INT(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * I_get(void *ptr, Py_ssize_t size) { - unsigned int val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned int val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } static PyObject * I_get_sw(void *ptr, Py_ssize_t size) { - unsigned int val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_INT(val); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned int val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_INT(val); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } static PyObject * l_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - long x; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + long val; + long x; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * l_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - long field; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_LONG(field); - field = (long)SET(field, val, size); - field = SWAP_LONG(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + long val; + long field; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_LONG(field); + field = (long)SET(field, val, size); + field = SWAP_LONG(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * l_get(void *ptr, Py_ssize_t size) { - long val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + long val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * l_get_sw(void *ptr, Py_ssize_t size) { - long val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_LONG(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + long val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_LONG(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * L_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned long x; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned long val; + unsigned long x; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * L_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned long field; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_LONG(field); - field = (unsigned long)SET(field, val, size); - field = SWAP_LONG(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned long val; + unsigned long field; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_LONG(field); + field = (unsigned long)SET(field, val, size); + field = SWAP_LONG(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * L_get(void *ptr, Py_ssize_t size) { - unsigned long val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned long val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } static PyObject * L_get_sw(void *ptr, Py_ssize_t size) { - unsigned long val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_LONG(val); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned long val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_LONG(val); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } #ifdef HAVE_LONG_LONG static PyObject * q_set(void *ptr, PyObject *value, Py_ssize_t size) { - PY_LONG_LONG val; - PY_LONG_LONG x; - if (get_longlong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + PY_LONG_LONG val; + PY_LONG_LONG x; + if (get_longlong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * q_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - PY_LONG_LONG val; - PY_LONG_LONG field; - if (get_longlong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_8(field); - field = (PY_LONG_LONG)SET(field, val, size); - field = SWAP_8(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + PY_LONG_LONG val; + PY_LONG_LONG field; + if (get_longlong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_8(field); + field = (PY_LONG_LONG)SET(field, val, size); + field = SWAP_8(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * q_get(void *ptr, Py_ssize_t size) { - PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLongLong(val); + PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLongLong(val); } static PyObject * q_get_sw(void *ptr, Py_ssize_t size) { - PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_8(val); - GET_BITFIELD(val, size); - return PyLong_FromLongLong(val); + PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_8(val); + GET_BITFIELD(val, size); + return PyLong_FromLongLong(val); } static PyObject * Q_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - unsigned PY_LONG_LONG x; - if (get_ulonglong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned PY_LONG_LONG val; + unsigned PY_LONG_LONG x; + if (get_ulonglong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * Q_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - unsigned PY_LONG_LONG field; - if (get_ulonglong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_8(field); - field = (unsigned PY_LONG_LONG)SET(field, val, size); - field = SWAP_8(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned PY_LONG_LONG val; + unsigned PY_LONG_LONG field; + if (get_ulonglong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_8(field); + field = (unsigned PY_LONG_LONG)SET(field, val, size); + field = SWAP_8(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * Q_get(void *ptr, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLongLong(val); + unsigned PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLongLong(val); } static PyObject * Q_get_sw(void *ptr, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_8(val); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLongLong(val); + unsigned PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_8(val); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLongLong(val); } #endif @@ -997,136 +997,136 @@ Q_get_sw(void *ptr, Py_ssize_t size) static PyObject * g_set(void *ptr, PyObject *value, Py_ssize_t size) { - long double x; + long double x; - x = PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - memcpy(ptr, &x, sizeof(long double)); - _RET(value); + x = PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + memcpy(ptr, &x, sizeof(long double)); + _RET(value); } static PyObject * g_get(void *ptr, Py_ssize_t size) { - long double val; - memcpy(&val, ptr, sizeof(long double)); - return PyFloat_FromDouble(val); + long double val; + memcpy(&val, ptr, sizeof(long double)); + return PyFloat_FromDouble(val); } static PyObject * d_set(void *ptr, PyObject *value, Py_ssize_t size) { - double x; + double x; - x = PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - memcpy(ptr, &x, sizeof(double)); - _RET(value); + x = PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + memcpy(ptr, &x, sizeof(double)); + _RET(value); } static PyObject * d_get(void *ptr, Py_ssize_t size) { - double val; - memcpy(&val, ptr, sizeof(val)); - return PyFloat_FromDouble(val); + double val; + memcpy(&val, ptr, sizeof(val)); + return PyFloat_FromDouble(val); } static PyObject * d_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - double x; + double x; - x = PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } + x = PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } #ifdef WORDS_BIGENDIAN - if (_PyFloat_Pack8(x, (unsigned char *)ptr, 1)) - return NULL; + if (_PyFloat_Pack8(x, (unsigned char *)ptr, 1)) + return NULL; #else - if (_PyFloat_Pack8(x, (unsigned char *)ptr, 0)) - return NULL; + if (_PyFloat_Pack8(x, (unsigned char *)ptr, 0)) + return NULL; #endif - _RET(value); + _RET(value); } static PyObject * d_get_sw(void *ptr, Py_ssize_t size) { #ifdef WORDS_BIGENDIAN - return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 1)); + return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 1)); #else - return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 0)); + return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 0)); #endif } static PyObject * f_set(void *ptr, PyObject *value, Py_ssize_t size) { - float x; + float x; - x = (float)PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - memcpy(ptr, &x, sizeof(x)); - _RET(value); + x = (float)PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * f_get(void *ptr, Py_ssize_t size) { - float val; - memcpy(&val, ptr, sizeof(val)); - return PyFloat_FromDouble(val); + float val; + memcpy(&val, ptr, sizeof(val)); + return PyFloat_FromDouble(val); } static PyObject * f_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - float x; + float x; - x = (float)PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } + x = (float)PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } #ifdef WORDS_BIGENDIAN - if (_PyFloat_Pack4(x, (unsigned char *)ptr, 1)) - return NULL; + if (_PyFloat_Pack4(x, (unsigned char *)ptr, 1)) + return NULL; #else - if (_PyFloat_Pack4(x, (unsigned char *)ptr, 0)) - return NULL; + if (_PyFloat_Pack4(x, (unsigned char *)ptr, 0)) + return NULL; #endif - _RET(value); + _RET(value); } static PyObject * f_get_sw(void *ptr, Py_ssize_t size) { #ifdef WORDS_BIGENDIAN - return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 1)); + return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 1)); #else - return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 0)); + return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 0)); #endif } @@ -1143,72 +1143,72 @@ f_get_sw(void *ptr, Py_ssize_t size) static PyObject * O_get(void *ptr, Py_ssize_t size) { - PyObject *ob = *(PyObject **)ptr; - if (ob == NULL) { - if (!PyErr_Occurred()) - /* Set an error if not yet set */ - PyErr_SetString(PyExc_ValueError, - "PyObject is NULL"); - return NULL; - } - Py_INCREF(ob); - return ob; + PyObject *ob = *(PyObject **)ptr; + if (ob == NULL) { + if (!PyErr_Occurred()) + /* Set an error if not yet set */ + PyErr_SetString(PyExc_ValueError, + "PyObject is NULL"); + return NULL; + } + Py_INCREF(ob); + return ob; } static PyObject * O_set(void *ptr, PyObject *value, Py_ssize_t size) { - /* Hm, does the memory block need it's own refcount or not? */ - *(PyObject **)ptr = value; - Py_INCREF(value); - return value; + /* Hm, does the memory block need it's own refcount or not? */ + *(PyObject **)ptr = value; + Py_INCREF(value); + return value; } static PyObject * c_set(void *ptr, PyObject *value, Py_ssize_t size) { - if (PyUnicode_Check(value)) { - value = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (value == NULL) - return NULL; - if (PyBytes_GET_SIZE(value) != 1) { - Py_DECREF(value); - goto error; - } - *(char *)ptr = PyBytes_AS_STRING(value)[0]; - Py_DECREF(value); - _RET(value); - } - if (PyBytes_Check(value) && PyBytes_GET_SIZE(value) == 1) { - *(char *)ptr = PyBytes_AS_STRING(value)[0]; - _RET(value); - } - if (PyByteArray_Check(value) && PyByteArray_GET_SIZE(value) == 1) { - *(char *)ptr = PyByteArray_AS_STRING(value)[0]; - _RET(value); - } - if (PyLong_Check(value)) - { - long longval = PyLong_AS_LONG(value); - if (longval < 0 || longval >= 256) - goto error; - *(char *)ptr = (char)longval; - _RET(value); - } + if (PyUnicode_Check(value)) { + value = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (value == NULL) + return NULL; + if (PyBytes_GET_SIZE(value) != 1) { + Py_DECREF(value); + goto error; + } + *(char *)ptr = PyBytes_AS_STRING(value)[0]; + Py_DECREF(value); + _RET(value); + } + if (PyBytes_Check(value) && PyBytes_GET_SIZE(value) == 1) { + *(char *)ptr = PyBytes_AS_STRING(value)[0]; + _RET(value); + } + if (PyByteArray_Check(value) && PyByteArray_GET_SIZE(value) == 1) { + *(char *)ptr = PyByteArray_AS_STRING(value)[0]; + _RET(value); + } + if (PyLong_Check(value)) + { + long longval = PyLong_AS_LONG(value); + if (longval < 0 || longval >= 256) + goto error; + *(char *)ptr = (char)longval; + _RET(value); + } error: - PyErr_Format(PyExc_TypeError, - "one character string expected"); - return NULL; + PyErr_Format(PyExc_TypeError, + "one character string expected"); + return NULL; } static PyObject * c_get(void *ptr, Py_ssize_t size) { - return PyBytes_FromStringAndSize((char *)ptr, 1); + return PyBytes_FromStringAndSize((char *)ptr, 1); } #ifdef CTYPES_UNICODE @@ -1216,107 +1216,107 @@ c_get(void *ptr, Py_ssize_t size) static PyObject * u_set(void *ptr, PyObject *value, Py_ssize_t size) { - Py_ssize_t len; - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } else - Py_INCREF(value); + Py_ssize_t len; + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } else + Py_INCREF(value); - len = PyUnicode_GET_SIZE(value); - if (len != 1) { - Py_DECREF(value); - PyErr_SetString(PyExc_TypeError, - "one character unicode string expected"); - return NULL; - } + len = PyUnicode_GET_SIZE(value); + if (len != 1) { + Py_DECREF(value); + PyErr_SetString(PyExc_TypeError, + "one character unicode string expected"); + return NULL; + } - *(wchar_t *)ptr = PyUnicode_AS_UNICODE(value)[0]; - Py_DECREF(value); + *(wchar_t *)ptr = PyUnicode_AS_UNICODE(value)[0]; + Py_DECREF(value); - _RET(value); + _RET(value); } static PyObject * u_get(void *ptr, Py_ssize_t size) { - return PyUnicode_FromWideChar((wchar_t *)ptr, 1); + return PyUnicode_FromWideChar((wchar_t *)ptr, 1); } /* U - a unicode string */ static PyObject * U_get(void *ptr, Py_ssize_t size) { - PyObject *result; - Py_ssize_t len; - Py_UNICODE *p; + PyObject *result; + Py_ssize_t len; + Py_UNICODE *p; - size /= sizeof(wchar_t); /* we count character units here, not bytes */ + size /= sizeof(wchar_t); /* we count character units here, not bytes */ - result = PyUnicode_FromWideChar((wchar_t *)ptr, size); - if (!result) - return NULL; - /* We need 'result' to be able to count the characters with wcslen, - since ptr may not be NUL terminated. If the length is smaller (if - it was actually NUL terminated, we construct a new one and throw - away the result. - */ - /* chop off at the first NUL character, if any. */ - p = PyUnicode_AS_UNICODE(result); - for (len = 0; len < size; ++len) - if (!p[len]) - break; + result = PyUnicode_FromWideChar((wchar_t *)ptr, size); + if (!result) + return NULL; + /* We need 'result' to be able to count the characters with wcslen, + since ptr may not be NUL terminated. If the length is smaller (if + it was actually NUL terminated, we construct a new one and throw + away the result. + */ + /* chop off at the first NUL character, if any. */ + p = PyUnicode_AS_UNICODE(result); + for (len = 0; len < size; ++len) + if (!p[len]) + break; - if (len < size) { - PyObject *ob = PyUnicode_FromWideChar((wchar_t *)ptr, len); - Py_DECREF(result); - return ob; - } - return result; + if (len < size) { + PyObject *ob = PyUnicode_FromWideChar((wchar_t *)ptr, len); + Py_DECREF(result); + return ob; + } + return result; } static PyObject * U_set(void *ptr, PyObject *value, Py_ssize_t length) { - Py_ssize_t size; - - /* It's easier to calculate in characters than in bytes */ - length /= sizeof(wchar_t); - - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } else - Py_INCREF(value); - size = PyUnicode_GET_SIZE(value); - if (size > length) { - PyErr_Format(PyExc_ValueError, - "string too long (%zd, maximum length %zd)", - size, length); - Py_DECREF(value); - return NULL; - } else if (size < length-1) - /* copy terminating NUL character if there is space */ - size += 1; - PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size); - return value; + Py_ssize_t size; + + /* It's easier to calculate in characters than in bytes */ + length /= sizeof(wchar_t); + + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } else + Py_INCREF(value); + size = PyUnicode_GET_SIZE(value); + if (size > length) { + PyErr_Format(PyExc_ValueError, + "string too long (%zd, maximum length %zd)", + size, length); + Py_DECREF(value); + return NULL; + } else if (size < length-1) + /* copy terminating NUL character if there is space */ + size += 1; + PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size); + return value; } #endif @@ -1324,210 +1324,210 @@ U_set(void *ptr, PyObject *value, Py_ssize_t length) static PyObject * s_get(void *ptr, Py_ssize_t size) { - Py_ssize_t i; - char *p; + Py_ssize_t i; + char *p; - p = (char *)ptr; - for (i = 0; i < size; ++i) { - if (*p++ == '\0') - break; - } + p = (char *)ptr; + for (i = 0; i < size; ++i) { + if (*p++ == '\0') + break; + } - return PyUnicode_FromStringAndSize((char *)ptr, (Py_ssize_t)i); + return PyUnicode_FromStringAndSize((char *)ptr, (Py_ssize_t)i); } static PyObject * s_set(void *ptr, PyObject *value, Py_ssize_t length) { - char *data; - Py_ssize_t size; - - if (PyUnicode_Check(value)) { - value = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (value == NULL) - return NULL; - assert(PyBytes_Check(value)); - } else if(PyBytes_Check(value)) { - Py_INCREF(value); - } else { - PyErr_Format(PyExc_TypeError, - "expected string, %s found", - value->ob_type->tp_name); - return NULL; - } - - data = PyBytes_AS_STRING(value); - if (!data) - return NULL; - size = strlen(data); /* XXX Why not Py_SIZE(value)? */ - if (size < length) { - /* This will copy the leading NUL character - * if there is space for it. - */ - ++size; - } else if (size > length) { - PyErr_Format(PyExc_ValueError, - "string too long (%zd, maximum length %zd)", - size, length); - Py_DECREF(value); - return NULL; - } - /* Also copy the terminating NUL character if there is space */ - memcpy((char *)ptr, data, size); - - Py_DECREF(value); - _RET(value); + char *data; + Py_ssize_t size; + + if (PyUnicode_Check(value)) { + value = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (value == NULL) + return NULL; + assert(PyBytes_Check(value)); + } else if(PyBytes_Check(value)) { + Py_INCREF(value); + } else { + PyErr_Format(PyExc_TypeError, + "expected string, %s found", + value->ob_type->tp_name); + return NULL; + } + + data = PyBytes_AS_STRING(value); + if (!data) + return NULL; + size = strlen(data); /* XXX Why not Py_SIZE(value)? */ + if (size < length) { + /* This will copy the leading NUL character + * if there is space for it. + */ + ++size; + } else if (size > length) { + PyErr_Format(PyExc_ValueError, + "string too long (%zd, maximum length %zd)", + size, length); + Py_DECREF(value); + return NULL; + } + /* Also copy the terminating NUL character if there is space */ + memcpy((char *)ptr, data, size); + + Py_DECREF(value); + _RET(value); } static PyObject * z_set(void *ptr, PyObject *value, Py_ssize_t size) { - if (value == Py_None) { - *(char **)ptr = NULL; - Py_INCREF(value); - return value; - } - if (PyBytes_Check(value)) { - *(char **)ptr = PyBytes_AsString(value); - Py_INCREF(value); - return value; - } else if (PyUnicode_Check(value)) { - PyObject *str = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (str == NULL) - return NULL; - *(char **)ptr = PyBytes_AS_STRING(str); - return str; - } else if (PyLong_Check(value)) { + if (value == Py_None) { + *(char **)ptr = NULL; + Py_INCREF(value); + return value; + } + if (PyBytes_Check(value)) { + *(char **)ptr = PyBytes_AsString(value); + Py_INCREF(value); + return value; + } else if (PyUnicode_Check(value)) { + PyObject *str = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (str == NULL) + return NULL; + *(char **)ptr = PyBytes_AS_STRING(str); + return str; + } else if (PyLong_Check(value)) { #if SIZEOF_VOID_P == SIZEOF_LONG_LONG - *(char **)ptr = (char *)PyLong_AsUnsignedLongLongMask(value); + *(char **)ptr = (char *)PyLong_AsUnsignedLongLongMask(value); #else - *(char **)ptr = (char *)PyLong_AsUnsignedLongMask(value); + *(char **)ptr = (char *)PyLong_AsUnsignedLongMask(value); #endif - _RET(value); - } - PyErr_Format(PyExc_TypeError, - "string or integer address expected instead of %s instance", - value->ob_type->tp_name); - return NULL; + _RET(value); + } + PyErr_Format(PyExc_TypeError, + "string or integer address expected instead of %s instance", + value->ob_type->tp_name); + return NULL; } static PyObject * z_get(void *ptr, Py_ssize_t size) { - /* XXX What about invalid pointers ??? */ - if (*(void **)ptr) { + /* XXX What about invalid pointers ??? */ + if (*(void **)ptr) { #if defined(MS_WIN32) && !defined(_WIN32_WCE) - if (IsBadStringPtrA(*(char **)ptr, -1)) { - PyErr_Format(PyExc_ValueError, - "invalid string pointer %p", - *(char **)ptr); - return NULL; - } + if (IsBadStringPtrA(*(char **)ptr, -1)) { + PyErr_Format(PyExc_ValueError, + "invalid string pointer %p", + *(char **)ptr); + return NULL; + } #endif - return PyBytes_FromStringAndSize(*(char **)ptr, - strlen(*(char **)ptr)); - } else { - Py_INCREF(Py_None); - return Py_None; - } + return PyBytes_FromStringAndSize(*(char **)ptr, + strlen(*(char **)ptr)); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #ifdef CTYPES_UNICODE static PyObject * Z_set(void *ptr, PyObject *value, Py_ssize_t size) { - if (value == Py_None) { - *(wchar_t **)ptr = NULL; - Py_INCREF(value); - return value; - } - if (PyLong_Check(value) || PyLong_Check(value)) { + if (value == Py_None) { + *(wchar_t **)ptr = NULL; + Py_INCREF(value); + return value; + } + if (PyLong_Check(value) || PyLong_Check(value)) { #if SIZEOF_VOID_P == SIZEOF_LONG_LONG - *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongLongMask(value); + *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongLongMask(value); #else - *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongMask(value); + *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongMask(value); #endif - Py_INCREF(Py_None); - return Py_None; - } - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string or integer address expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } else - Py_INCREF(value); + Py_INCREF(Py_None); + return Py_None; + } + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string or integer address expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } else + Py_INCREF(value); #ifdef HAVE_USABLE_WCHAR_T - /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same - type. So we can copy directly. Hm, are unicode objects always NUL - terminated in Python, internally? - */ - *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value); - return value; + /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same + type. So we can copy directly. Hm, are unicode objects always NUL + terminated in Python, internally? + */ + *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value); + return value; #else - { - /* We must create a wchar_t* buffer from the unicode object, - and keep it alive */ - PyObject *keep; - wchar_t *buffer; - - int size = PyUnicode_GET_SIZE(value); - size += 1; /* terminating NUL */ - size *= sizeof(wchar_t); - buffer = (wchar_t *)PyMem_Malloc(size); - if (!buffer) { - Py_DECREF(value); - return PyErr_NoMemory(); - } - memset(buffer, 0, size); - keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor); - if (!keep) { - Py_DECREF(value); - PyMem_Free(buffer); - return NULL; - } - *(wchar_t **)ptr = (wchar_t *)buffer; - if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value, - buffer, PyUnicode_GET_SIZE(value))) { - Py_DECREF(value); - Py_DECREF(keep); - return NULL; - } - Py_DECREF(value); - return keep; - } + { + /* We must create a wchar_t* buffer from the unicode object, + and keep it alive */ + PyObject *keep; + wchar_t *buffer; + + int size = PyUnicode_GET_SIZE(value); + size += 1; /* terminating NUL */ + size *= sizeof(wchar_t); + buffer = (wchar_t *)PyMem_Malloc(size); + if (!buffer) { + Py_DECREF(value); + return PyErr_NoMemory(); + } + memset(buffer, 0, size); + keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor); + if (!keep) { + Py_DECREF(value); + PyMem_Free(buffer); + return NULL; + } + *(wchar_t **)ptr = (wchar_t *)buffer; + if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value, + buffer, PyUnicode_GET_SIZE(value))) { + Py_DECREF(value); + Py_DECREF(keep); + return NULL; + } + Py_DECREF(value); + return keep; + } #endif } static PyObject * Z_get(void *ptr, Py_ssize_t size) { - wchar_t *p; - p = *(wchar_t **)ptr; - if (p) { + wchar_t *p; + p = *(wchar_t **)ptr; + if (p) { #if defined(MS_WIN32) && !defined(_WIN32_WCE) - if (IsBadStringPtrW(*(wchar_t **)ptr, -1)) { - PyErr_Format(PyExc_ValueError, - "invalid string pointer %p", - *(wchar_t **)ptr); - return NULL; - } + if (IsBadStringPtrW(*(wchar_t **)ptr, -1)) { + PyErr_Format(PyExc_ValueError, + "invalid string pointer %p", + *(wchar_t **)ptr); + return NULL; + } #endif - return PyUnicode_FromWideChar(p, wcslen(p)); - } else { - Py_INCREF(Py_None); - return Py_None; - } + return PyUnicode_FromWideChar(p, wcslen(p)); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif @@ -1535,166 +1535,166 @@ Z_get(void *ptr, Py_ssize_t size) static PyObject * BSTR_set(void *ptr, PyObject *value, Py_ssize_t size) { - BSTR bstr; - - /* convert value into a PyUnicodeObject or NULL */ - if (Py_None == value) { - value = NULL; - } else if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (PyUnicode_Check(value)) { - Py_INCREF(value); /* for the descref below */ - } else { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - - /* create a BSTR from value */ - if (value) { - Py_ssize_t size = PyUnicode_GET_SIZE(value); - if ((unsigned) size != size) { - PyErr_SetString(PyExc_ValueError, "String too long for BSTR"); - return NULL; - } - bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value), - (unsigned)size); - Py_DECREF(value); - } else - bstr = NULL; - - /* free the previous contents, if any */ - if (*(BSTR *)ptr) - SysFreeString(*(BSTR *)ptr); - - /* and store it */ - *(BSTR *)ptr = bstr; - - /* We don't need to keep any other object */ - _RET(value); + BSTR bstr; + + /* convert value into a PyUnicodeObject or NULL */ + if (Py_None == value) { + value = NULL; + } else if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (PyUnicode_Check(value)) { + Py_INCREF(value); /* for the descref below */ + } else { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + + /* create a BSTR from value */ + if (value) { + Py_ssize_t size = PyUnicode_GET_SIZE(value); + if ((unsigned) size != size) { + PyErr_SetString(PyExc_ValueError, "String too long for BSTR"); + return NULL; + } + bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value), + (unsigned)size); + Py_DECREF(value); + } else + bstr = NULL; + + /* free the previous contents, if any */ + if (*(BSTR *)ptr) + SysFreeString(*(BSTR *)ptr); + + /* and store it */ + *(BSTR *)ptr = bstr; + + /* We don't need to keep any other object */ + _RET(value); } static PyObject * BSTR_get(void *ptr, Py_ssize_t size) { - BSTR p; - p = *(BSTR *)ptr; - if (p) - return PyUnicode_FromWideChar(p, SysStringLen(p)); - else { - /* Hm, it seems NULL pointer and zero length string are the - same in BSTR, see Don Box, p 81 - */ - Py_INCREF(Py_None); - return Py_None; - } + BSTR p; + p = *(BSTR *)ptr; + if (p) + return PyUnicode_FromWideChar(p, SysStringLen(p)); + else { + /* Hm, it seems NULL pointer and zero length string are the + same in BSTR, see Don Box, p 81 + */ + Py_INCREF(Py_None); + return Py_None; + } } #endif static PyObject * P_set(void *ptr, PyObject *value, Py_ssize_t size) { - void *v; - if (value == Py_None) { - *(void **)ptr = NULL; - _RET(value); - } + void *v; + if (value == Py_None) { + *(void **)ptr = NULL; + _RET(value); + } - if (!PyLong_Check(value) && !PyLong_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "cannot be converted to pointer"); - return NULL; - } + if (!PyLong_Check(value) && !PyLong_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "cannot be converted to pointer"); + return NULL; + } #if SIZEOF_VOID_P <= SIZEOF_LONG - v = (void *)PyLong_AsUnsignedLongMask(value); + v = (void *)PyLong_AsUnsignedLongMask(value); #else #ifndef HAVE_LONG_LONG # error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long" #elif SIZEOF_LONG_LONG < SIZEOF_VOID_P # error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)" #endif - v = (void *)PyLong_AsUnsignedLongLongMask(value); + v = (void *)PyLong_AsUnsignedLongLongMask(value); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - *(void **)ptr = v; - _RET(value); + *(void **)ptr = v; + _RET(value); } static PyObject * P_get(void *ptr, Py_ssize_t size) { - if (*(void **)ptr == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyLong_FromVoidPtr(*(void **)ptr); + if (*(void **)ptr == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyLong_FromVoidPtr(*(void **)ptr); } static struct fielddesc formattable[] = { - { 's', s_set, s_get, &ffi_type_pointer}, - { 'b', b_set, b_get, &ffi_type_schar}, - { 'B', B_set, B_get, &ffi_type_uchar}, - { 'c', c_set, c_get, &ffi_type_schar}, - { 'd', d_set, d_get, &ffi_type_double, d_set_sw, d_get_sw}, - { 'g', g_set, g_get, &ffi_type_longdouble}, - { 'f', f_set, f_get, &ffi_type_float, f_set_sw, f_get_sw}, - { 'h', h_set, h_get, &ffi_type_sshort, h_set_sw, h_get_sw}, - { 'H', H_set, H_get, &ffi_type_ushort, H_set_sw, H_get_sw}, - { 'i', i_set, i_get, &ffi_type_sint, i_set_sw, i_get_sw}, - { 'I', I_set, I_get, &ffi_type_uint, I_set_sw, I_get_sw}, + { 's', s_set, s_get, &ffi_type_pointer}, + { 'b', b_set, b_get, &ffi_type_schar}, + { 'B', B_set, B_get, &ffi_type_uchar}, + { 'c', c_set, c_get, &ffi_type_schar}, + { 'd', d_set, d_get, &ffi_type_double, d_set_sw, d_get_sw}, + { 'g', g_set, g_get, &ffi_type_longdouble}, + { 'f', f_set, f_get, &ffi_type_float, f_set_sw, f_get_sw}, + { 'h', h_set, h_get, &ffi_type_sshort, h_set_sw, h_get_sw}, + { 'H', H_set, H_get, &ffi_type_ushort, H_set_sw, H_get_sw}, + { 'i', i_set, i_get, &ffi_type_sint, i_set_sw, i_get_sw}, + { 'I', I_set, I_get, &ffi_type_uint, I_set_sw, I_get_sw}, /* XXX Hm, sizeof(int) == sizeof(long) doesn't hold on every platform */ /* As soon as we can get rid of the type codes, this is no longer a problem */ #if SIZEOF_LONG == 4 - { 'l', l_set, l_get, &ffi_type_sint32, l_set_sw, l_get_sw}, - { 'L', L_set, L_get, &ffi_type_uint32, L_set_sw, L_get_sw}, + { 'l', l_set, l_get, &ffi_type_sint32, l_set_sw, l_get_sw}, + { 'L', L_set, L_get, &ffi_type_uint32, L_set_sw, L_get_sw}, #elif SIZEOF_LONG == 8 - { 'l', l_set, l_get, &ffi_type_sint64, l_set_sw, l_get_sw}, - { 'L', L_set, L_get, &ffi_type_uint64, L_set_sw, L_get_sw}, + { 'l', l_set, l_get, &ffi_type_sint64, l_set_sw, l_get_sw}, + { 'L', L_set, L_get, &ffi_type_uint64, L_set_sw, L_get_sw}, #else # error #endif #ifdef HAVE_LONG_LONG #if SIZEOF_LONG_LONG == 8 - { 'q', q_set, q_get, &ffi_type_sint64, q_set_sw, q_get_sw}, - { 'Q', Q_set, Q_get, &ffi_type_uint64, Q_set_sw, Q_get_sw}, + { 'q', q_set, q_get, &ffi_type_sint64, q_set_sw, q_get_sw}, + { 'Q', Q_set, Q_get, &ffi_type_uint64, Q_set_sw, Q_get_sw}, #else # error #endif #endif - { 'P', P_set, P_get, &ffi_type_pointer}, - { 'z', z_set, z_get, &ffi_type_pointer}, + { 'P', P_set, P_get, &ffi_type_pointer}, + { 'z', z_set, z_get, &ffi_type_pointer}, #ifdef CTYPES_UNICODE - { 'u', u_set, u_get, NULL}, /* ffi_type set later */ - { 'U', U_set, U_get, &ffi_type_pointer}, - { 'Z', Z_set, Z_get, &ffi_type_pointer}, + { 'u', u_set, u_get, NULL}, /* ffi_type set later */ + { 'U', U_set, U_get, &ffi_type_pointer}, + { 'Z', Z_set, Z_get, &ffi_type_pointer}, #endif #ifdef MS_WIN32 - { 'X', BSTR_set, BSTR_get, &ffi_type_pointer}, - { 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort}, + { 'X', BSTR_set, BSTR_get, &ffi_type_pointer}, + { 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort}, #endif #if SIZEOF__BOOL == 1 - { '?', bool_set, bool_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */ + { '?', bool_set, bool_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */ #elif SIZEOF__BOOL == SIZEOF_SHORT - { '?', bool_set, bool_get, &ffi_type_ushort}, + { '?', bool_set, bool_get, &ffi_type_ushort}, #elif SIZEOF__BOOL == SIZEOF_INT - { '?', bool_set, bool_get, &ffi_type_uint, I_set_sw, I_get_sw}, + { '?', bool_set, bool_get, &ffi_type_uint, I_set_sw, I_get_sw}, #elif SIZEOF__BOOL == SIZEOF_LONG - { '?', bool_set, bool_get, &ffi_type_ulong, L_set_sw, L_get_sw}, + { '?', bool_set, bool_get, &ffi_type_ulong, L_set_sw, L_get_sw}, #elif SIZEOF__BOOL == SIZEOF_LONG_LONG - { '?', bool_set, bool_get, &ffi_type_ulong, Q_set_sw, Q_get_sw}, + { '?', bool_set, bool_get, &ffi_type_ulong, Q_set_sw, Q_get_sw}, #endif /* SIZEOF__BOOL */ - { 'O', O_set, O_get, &ffi_type_pointer}, - { 0, NULL, NULL, NULL}, + { 'O', O_set, O_get, &ffi_type_pointer}, + { 0, NULL, NULL, NULL}, }; /* @@ -1705,26 +1705,26 @@ static struct fielddesc formattable[] = { struct fielddesc * _ctypes_get_fielddesc(const char *fmt) { - static int initialized = 0; - struct fielddesc *table = formattable; + static int initialized = 0; + struct fielddesc *table = formattable; - if (!initialized) { - initialized = 1; + if (!initialized) { + initialized = 1; #ifdef CTYPES_UNICODE - if (sizeof(wchar_t) == sizeof(short)) - _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sshort; - else if (sizeof(wchar_t) == sizeof(int)) - _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sint; - else if (sizeof(wchar_t) == sizeof(long)) - _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_slong; + if (sizeof(wchar_t) == sizeof(short)) + _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sshort; + else if (sizeof(wchar_t) == sizeof(int)) + _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sint; + else if (sizeof(wchar_t) == sizeof(long)) + _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_slong; #endif - } + } - for (; table->code; ++table) { - if (table->code == fmt[0]) - return table; - } - return NULL; + for (; table->code; ++table) { + if (table->code == fmt[0]) + return table; + } + return NULL; } typedef struct { char c; char x; } s_char; @@ -1768,10 +1768,10 @@ typedef struct { char c; PY_LONG_LONG x; } s_long_long; /* from ffi.h: typedef struct _ffi_type { - size_t size; - unsigned short alignment; - unsigned short type; - struct _ffi_type **elements; + size_t size; + unsigned short alignment; + unsigned short type; + struct _ffi_type **elements; } ffi_type; */ @@ -1798,7 +1798,7 @@ ffi_type ffi_type_double = { sizeof(double), DOUBLE_ALIGN, FFI_TYPE_DOUBLE }; #endif /* This is already defined on OSX */ ffi_type ffi_type_longdouble = { sizeof(long double), LONGDOUBLE_ALIGN, - FFI_TYPE_LONGDOUBLE }; + FFI_TYPE_LONGDOUBLE }; ffi_type ffi_type_pointer = { sizeof(void *), VOID_P_ALIGN, FFI_TYPE_POINTER }; diff --git a/Modules/_ctypes/ctypes.h b/Modules/_ctypes/ctypes.h index b4047a4..e0bad07 100644 --- a/Modules/_ctypes/ctypes.h +++ b/Modules/_ctypes/ctypes.h @@ -21,16 +21,16 @@ Making CDataObject a variable size object would be a better solution, but more difficult in the presence of PyCFuncPtrObject. Maybe later. */ union value { - char c[16]; - short s; - int i; - long l; - float f; - double d; + char c[16]; + short s; + int i; + long l; + float f; + double d; #ifdef HAVE_LONG_LONG - PY_LONG_LONG ll; + PY_LONG_LONG ll; #endif - long double D; + long double D; }; /* @@ -40,67 +40,67 @@ union value { */ struct tagCDataObject { - PyObject_HEAD - char *b_ptr; /* pointer to memory block */ - int b_needsfree; /* need _we_ free the memory? */ - CDataObject *b_base; /* pointer to base object or NULL */ - Py_ssize_t b_size; /* size of memory block in bytes */ - Py_ssize_t b_length; /* number of references we need */ - Py_ssize_t b_index; /* index of this object into base's - b_object list */ - PyObject *b_objects; /* dictionary of references we need to keep, or Py_None */ - union value b_value; + PyObject_HEAD + char *b_ptr; /* pointer to memory block */ + int b_needsfree; /* need _we_ free the memory? */ + CDataObject *b_base; /* pointer to base object or NULL */ + Py_ssize_t b_size; /* size of memory block in bytes */ + Py_ssize_t b_length; /* number of references we need */ + Py_ssize_t b_index; /* index of this object into base's + b_object list */ + PyObject *b_objects; /* dictionary of references we need to keep, or Py_None */ + union value b_value; }; typedef struct { - PyObject_VAR_HEAD - ffi_closure *pcl; /* the C callable */ - ffi_cif cif; - int flags; - PyObject *converters; - PyObject *callable; - PyObject *restype; - SETFUNC setfunc; - ffi_type *ffi_restype; - ffi_type *atypes[1]; + PyObject_VAR_HEAD + ffi_closure *pcl; /* the C callable */ + ffi_cif cif; + int flags; + PyObject *converters; + PyObject *callable; + PyObject *restype; + SETFUNC setfunc; + ffi_type *ffi_restype; + ffi_type *atypes[1]; } CThunkObject; extern PyTypeObject PyCThunk_Type; -#define CThunk_CheckExact(v) ((v)->ob_type == &PyCThunk_Type) +#define CThunk_CheckExact(v) ((v)->ob_type == &PyCThunk_Type) typedef struct { - /* First part identical to tagCDataObject */ - PyObject_HEAD - char *b_ptr; /* pointer to memory block */ - int b_needsfree; /* need _we_ free the memory? */ - CDataObject *b_base; /* pointer to base object or NULL */ - Py_ssize_t b_size; /* size of memory block in bytes */ - Py_ssize_t b_length; /* number of references we need */ - Py_ssize_t b_index; /* index of this object into base's - b_object list */ - PyObject *b_objects; /* list of references we need to keep */ - union value b_value; - /* end of tagCDataObject, additional fields follow */ - - CThunkObject *thunk; - PyObject *callable; - - /* These two fields will override the ones in the type's stgdict if - they are set */ - PyObject *converters; - PyObject *argtypes; - PyObject *restype; - PyObject *checker; - PyObject *errcheck; + /* First part identical to tagCDataObject */ + PyObject_HEAD + char *b_ptr; /* pointer to memory block */ + int b_needsfree; /* need _we_ free the memory? */ + CDataObject *b_base; /* pointer to base object or NULL */ + Py_ssize_t b_size; /* size of memory block in bytes */ + Py_ssize_t b_length; /* number of references we need */ + Py_ssize_t b_index; /* index of this object into base's + b_object list */ + PyObject *b_objects; /* list of references we need to keep */ + union value b_value; + /* end of tagCDataObject, additional fields follow */ + + CThunkObject *thunk; + PyObject *callable; + + /* These two fields will override the ones in the type's stgdict if + they are set */ + PyObject *converters; + PyObject *argtypes; + PyObject *restype; + PyObject *checker; + PyObject *errcheck; #ifdef MS_WIN32 - int index; - GUID *iid; + int index; + GUID *iid; #endif - PyObject *paramflags; + PyObject *paramflags; } PyCFuncPtrObject; extern PyTypeObject PyCStgDict_Type; -#define PyCStgDict_CheckExact(v) ((v)->ob_type == &PyCStgDict_Type) -#define PyCStgDict_Check(v) PyObject_TypeCheck(v, &PyCStgDict_Type) +#define PyCStgDict_CheckExact(v) ((v)->ob_type == &PyCStgDict_Type) +#define PyCStgDict_Check(v) PyObject_TypeCheck(v, &PyCStgDict_Type) extern int PyCStructUnionType_update_stgdict(PyObject *fields, PyObject *type, int isStruct); extern int PyType_stginfo(PyTypeObject *self, Py_ssize_t *psize, Py_ssize_t *palign, Py_ssize_t *plength); @@ -109,12 +109,12 @@ extern int PyObject_stginfo(PyObject *self, Py_ssize_t *psize, Py_ssize_t *palig extern PyTypeObject PyCData_Type; -#define CDataObject_CheckExact(v) ((v)->ob_type == &PyCData_Type) -#define CDataObject_Check(v) PyObject_TypeCheck(v, &PyCData_Type) +#define CDataObject_CheckExact(v) ((v)->ob_type == &PyCData_Type) +#define CDataObject_Check(v) PyObject_TypeCheck(v, &PyCData_Type) extern PyTypeObject PyCSimpleType_Type; -#define PyCSimpleTypeObject_CheckExact(v) ((v)->ob_type == &PyCSimpleType_Type) -#define PyCSimpleTypeObject_Check(v) PyObject_TypeCheck(v, &PyCSimpleType_Type) +#define PyCSimpleTypeObject_CheckExact(v) ((v)->ob_type == &PyCSimpleType_Type) +#define PyCSimpleTypeObject_Check(v) PyObject_TypeCheck(v, &PyCSimpleType_Type) extern PyTypeObject PyCField_Type; extern struct fielddesc *_ctypes_get_fielddesc(const char *fmt); @@ -122,9 +122,9 @@ extern struct fielddesc *_ctypes_get_fielddesc(const char *fmt); extern PyObject * PyCField_FromDesc(PyObject *desc, Py_ssize_t index, - Py_ssize_t *pfield_size, int bitsize, int *pbitofs, - Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, - int pack, int is_big_endian); + Py_ssize_t *pfield_size, int bitsize, int *pbitofs, + Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, + int pack, int is_big_endian); extern PyObject *PyCData_AtAddress(PyObject *type, void *buf); extern PyObject *PyCData_FromBytes(PyObject *type, char *data, Py_ssize_t length); @@ -137,13 +137,13 @@ extern PyTypeObject PyCFuncPtr_Type; extern PyTypeObject PyCFuncPtrType_Type; extern PyTypeObject PyCStructType_Type; -#define PyCArrayTypeObject_Check(v) PyObject_TypeCheck(v, &PyCArrayType_Type) -#define ArrayObject_Check(v) PyObject_TypeCheck(v, &PyCArray_Type) -#define PointerObject_Check(v) PyObject_TypeCheck(v, &PyCPointer_Type) -#define PyCPointerTypeObject_Check(v) PyObject_TypeCheck(v, &PyCPointerType_Type) -#define PyCFuncPtrObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtr_Type) -#define PyCFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtrType_Type) -#define PyCStructTypeObject_Check(v) PyObject_TypeCheck(v, &PyCStructType_Type) +#define PyCArrayTypeObject_Check(v) PyObject_TypeCheck(v, &PyCArrayType_Type) +#define ArrayObject_Check(v) PyObject_TypeCheck(v, &PyCArray_Type) +#define PointerObject_Check(v) PyObject_TypeCheck(v, &PyCPointer_Type) +#define PyCPointerTypeObject_Check(v) PyObject_TypeCheck(v, &PyCPointerType_Type) +#define PyCFuncPtrObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtr_Type) +#define PyCFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtrType_Type) +#define PyCStructTypeObject_Check(v) PyObject_TypeCheck(v, &PyCStructType_Type) extern PyObject * PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length); @@ -151,35 +151,35 @@ PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length); extern PyMethodDef _ctypes_module_methods[]; extern CThunkObject *_ctypes_alloc_callback(PyObject *callable, - PyObject *converters, - PyObject *restype, - int flags); + PyObject *converters, + PyObject *restype, + int flags); /* a table entry describing a predefined ctypes type */ struct fielddesc { - char code; - SETFUNC setfunc; - GETFUNC getfunc; - ffi_type *pffi_type; /* always statically allocated */ - SETFUNC setfunc_swapped; - GETFUNC getfunc_swapped; + char code; + SETFUNC setfunc; + GETFUNC getfunc; + ffi_type *pffi_type; /* always statically allocated */ + SETFUNC setfunc_swapped; + GETFUNC getfunc_swapped; }; typedef struct { - PyObject_HEAD - Py_ssize_t offset; - Py_ssize_t size; - Py_ssize_t index; /* Index into CDataObject's - object array */ - PyObject *proto; /* a type or NULL */ - GETFUNC getfunc; /* getter function if proto is NULL */ - SETFUNC setfunc; /* setter function if proto is NULL */ - int anonymous; + PyObject_HEAD + Py_ssize_t offset; + Py_ssize_t size; + Py_ssize_t index; /* Index into CDataObject's + object array */ + PyObject *proto; /* a type or NULL */ + GETFUNC getfunc; /* getter function if proto is NULL */ + SETFUNC setfunc; /* setter function if proto is NULL */ + int anonymous; } CFieldObject; /* A subclass of PyDictObject, used as the instance dictionary of ctypes metatypes */ typedef struct { - PyDictObject dict; /* first part identical to PyDictObject */ + PyDictObject dict; /* first part identical to PyDictObject */ /* The size and align fields are unneeded, they are in ffi_type as well. As an experiment shows, it's trivial to get rid of them, the only thing to remember is that in PyCArrayType_new the ffi_type fields must be filled in - @@ -188,28 +188,28 @@ typedef struct { too much risk to change that now, and there are other fields which doen't belong into this structure anyway. Maybe in ctypes 2.0... (ctypes 2000?) */ - Py_ssize_t size; /* number of bytes */ - Py_ssize_t align; /* alignment requirements */ - Py_ssize_t length; /* number of fields */ - ffi_type ffi_type_pointer; - PyObject *proto; /* Only for Pointer/ArrayObject */ - SETFUNC setfunc; /* Only for simple objects */ - GETFUNC getfunc; /* Only for simple objects */ - PARAMFUNC paramfunc; - - /* Following fields only used by PyCFuncPtrType_Type instances */ - PyObject *argtypes; /* tuple of CDataObjects */ - PyObject *converters; /* tuple([t.from_param for t in argtypes]) */ - PyObject *restype; /* CDataObject or NULL */ - PyObject *checker; - int flags; /* calling convention and such */ - - /* pep3118 fields, pointers neeed PyMem_Free */ - char *format; - int ndim; - Py_ssize_t *shape; -/* Py_ssize_t *strides; */ /* unused in ctypes */ -/* Py_ssize_t *suboffsets; */ /* unused in ctypes */ + Py_ssize_t size; /* number of bytes */ + Py_ssize_t align; /* alignment requirements */ + Py_ssize_t length; /* number of fields */ + ffi_type ffi_type_pointer; + PyObject *proto; /* Only for Pointer/ArrayObject */ + SETFUNC setfunc; /* Only for simple objects */ + GETFUNC getfunc; /* Only for simple objects */ + PARAMFUNC paramfunc; + + /* Following fields only used by PyCFuncPtrType_Type instances */ + PyObject *argtypes; /* tuple of CDataObjects */ + PyObject *converters; /* tuple([t.from_param for t in argtypes]) */ + PyObject *restype; /* CDataObject or NULL */ + PyObject *checker; + int flags; /* calling convention and such */ + + /* pep3118 fields, pointers neeed PyMem_Free */ + char *format; + int ndim; + Py_ssize_t *shape; +/* Py_ssize_t *strides; */ /* unused in ctypes */ +/* Py_ssize_t *suboffsets; */ /* unused in ctypes */ } StgDictObject; @@ -264,16 +264,16 @@ extern int PyCStgDict_clone(StgDictObject *src, StgDictObject *dst); typedef int(* PPROC)(void); PyObject *_ctypes_callproc(PPROC pProc, - PyObject *arguments, + PyObject *arguments, #ifdef MS_WIN32 - IUnknown *pIUnk, - GUID *iid, + IUnknown *pIUnk, + GUID *iid, #endif - int flags, - PyObject *argtypes, - PyObject *restype, - PyObject *checker); - + int flags, + PyObject *argtypes, + PyObject *restype, + PyObject *checker); + #define FUNCFLAG_STDCALL 0x0 #define FUNCFLAG_CDECL 0x1 @@ -288,45 +288,45 @@ PyObject *_ctypes_callproc(PPROC pProc, #define DICTFLAG_FINAL 0x1000 struct tagPyCArgObject { - PyObject_HEAD - ffi_type *pffi_type; - char tag; - union { - char c; - char b; - short h; - int i; - long l; + PyObject_HEAD + ffi_type *pffi_type; + char tag; + union { + char c; + char b; + short h; + int i; + long l; #ifdef HAVE_LONG_LONG - PY_LONG_LONG q; + PY_LONG_LONG q; #endif - long double D; - double d; - float f; - void *p; - } value; - PyObject *obj; - Py_ssize_t size; /* for the 'V' tag */ + long double D; + double d; + float f; + void *p; + } value; + PyObject *obj; + Py_ssize_t size; /* for the 'V' tag */ }; extern PyTypeObject PyCArg_Type; -#define PyCArg_CheckExact(v) ((v)->ob_type == &PyCArg_Type) +#define PyCArg_CheckExact(v) ((v)->ob_type == &PyCArg_Type) extern PyCArgObject *PyCArgObject_new(void); extern PyObject * PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src, - Py_ssize_t index, Py_ssize_t size, char *ptr); + Py_ssize_t index, Py_ssize_t size, char *ptr); extern int PyCData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value, - Py_ssize_t index, Py_ssize_t size, char *ptr); + Py_ssize_t index, Py_ssize_t size, char *ptr); extern void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...); struct basespec { - CDataObject *base; - Py_ssize_t index; - char *adr; + CDataObject *base; + Py_ssize_t index; + char *adr; }; extern char basespec_string[]; diff --git a/Modules/_ctypes/darwin/dlfcn_simple.c b/Modules/_ctypes/darwin/dlfcn_simple.c index 4b55323..2b293bb 100644 --- a/Modules/_ctypes/darwin/dlfcn_simple.c +++ b/Modules/_ctypes/darwin/dlfcn_simple.c @@ -81,167 +81,167 @@ static const char *error(int setget, const char *str, ...); /* Set and get the error string for use by dlerror */ static const char *error(int setget, const char *str, ...) { - static char errstr[ERR_STR_LEN]; - static int err_filled = 0; - const char *retval; - va_list arg; - if (setget == 0) - { - va_start(arg, str); - strncpy(errstr, "dlcompat: ", ERR_STR_LEN); - vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg); - va_end(arg); - err_filled = 1; - retval = NULL; - } - else - { - if (!err_filled) - retval = NULL; - else - retval = errstr; - err_filled = 0; - } - return retval; + static char errstr[ERR_STR_LEN]; + static int err_filled = 0; + const char *retval; + va_list arg; + if (setget == 0) + { + va_start(arg, str); + strncpy(errstr, "dlcompat: ", ERR_STR_LEN); + vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg); + va_end(arg); + err_filled = 1; + retval = NULL; + } + else + { + if (!err_filled) + retval = NULL; + else + retval = errstr; + err_filled = 0; + } + return retval; } /* darwin_dlopen */ static void *darwin_dlopen(const char *path, int mode) { - void *module = 0; - NSObjectFileImage ofi = 0; - NSObjectFileImageReturnCode ofirc; + void *module = 0; + NSObjectFileImage ofi = 0; + NSObjectFileImageReturnCode ofirc; - /* If we got no path, the app wants the global namespace, use -1 as the marker - in this case */ - if (!path) - return (void *)-1; + /* If we got no path, the app wants the global namespace, use -1 as the marker + in this case */ + if (!path) + return (void *)-1; - /* Create the object file image, works for things linked with the -bundle arg to ld */ - ofirc = NSCreateObjectFileImageFromFile(path, &ofi); - switch (ofirc) - { - case NSObjectFileImageSuccess: - /* It was okay, so use NSLinkModule to link in the image */ - module = NSLinkModule(ofi, path, - NSLINKMODULE_OPTION_RETURN_ON_ERROR - | (mode & RTLD_GLOBAL) ? 0 : NSLINKMODULE_OPTION_PRIVATE - | (mode & RTLD_LAZY) ? 0 : NSLINKMODULE_OPTION_BINDNOW); - NSDestroyObjectFileImage(ofi); - break; - case NSObjectFileImageInappropriateFile: - /* It may have been a dynamic library rather than a bundle, try to load it */ - module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR); - break; - default: - /* God knows what we got */ - error(0, "Can not open \"%s\"", path); - return 0; - } - if (!module) - error(0, "Can not open \"%s\"", path); - return module; + /* Create the object file image, works for things linked with the -bundle arg to ld */ + ofirc = NSCreateObjectFileImageFromFile(path, &ofi); + switch (ofirc) + { + case NSObjectFileImageSuccess: + /* It was okay, so use NSLinkModule to link in the image */ + module = NSLinkModule(ofi, path, + NSLINKMODULE_OPTION_RETURN_ON_ERROR + | (mode & RTLD_GLOBAL) ? 0 : NSLINKMODULE_OPTION_PRIVATE + | (mode & RTLD_LAZY) ? 0 : NSLINKMODULE_OPTION_BINDNOW); + NSDestroyObjectFileImage(ofi); + break; + case NSObjectFileImageInappropriateFile: + /* It may have been a dynamic library rather than a bundle, try to load it */ + module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR); + break; + default: + /* God knows what we got */ + error(0, "Can not open \"%s\"", path); + return 0; + } + if (!module) + error(0, "Can not open \"%s\"", path); + return module; } /* dlsymIntern is used by dlsym to find the symbol */ static void *dlsymIntern(void *handle, const char *symbol) { - NSSymbol nssym = 0; - /* If the handle is -1, if is the app global context */ - if (handle == (void *)-1) - { - /* Global context, use NSLookupAndBindSymbol */ - if (NSIsSymbolNameDefined(symbol)) - { - nssym = NSLookupAndBindSymbol(symbol); - } + NSSymbol nssym = 0; + /* If the handle is -1, if is the app global context */ + if (handle == (void *)-1) + { + /* Global context, use NSLookupAndBindSymbol */ + if (NSIsSymbolNameDefined(symbol)) + { + nssym = NSLookupAndBindSymbol(symbol); + } - } - /* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image - for libraries, and NSLookupSymbolInModule for bundles */ - else - { - /* Check for both possible magic numbers depending on x86/ppc byte order */ - if ((((struct mach_header *)handle)->magic == MH_MAGIC) || - (((struct mach_header *)handle)->magic == MH_CIGAM)) - { - if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, symbol)) - { - nssym = NSLookupSymbolInImage((struct mach_header *)handle, - symbol, - NSLOOKUPSYMBOLINIMAGE_OPTION_BIND - | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); - } + } + /* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image + for libraries, and NSLookupSymbolInModule for bundles */ + else + { + /* Check for both possible magic numbers depending on x86/ppc byte order */ + if ((((struct mach_header *)handle)->magic == MH_MAGIC) || + (((struct mach_header *)handle)->magic == MH_CIGAM)) + { + if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, symbol)) + { + nssym = NSLookupSymbolInImage((struct mach_header *)handle, + symbol, + NSLOOKUPSYMBOLINIMAGE_OPTION_BIND + | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); + } - } - else - { - nssym = NSLookupSymbolInModule(handle, symbol); - } - } - if (!nssym) - { - error(0, "Symbol \"%s\" Not found", symbol); - return NULL; - } - return NSAddressOfSymbol(nssym); + } + else + { + nssym = NSLookupSymbolInModule(handle, symbol); + } + } + if (!nssym) + { + error(0, "Symbol \"%s\" Not found", symbol); + return NULL; + } + return NSAddressOfSymbol(nssym); } static const char *darwin_dlerror(void) { - return error(1, (char *)NULL); + return error(1, (char *)NULL); } static int darwin_dlclose(void *handle) { - if ((((struct mach_header *)handle)->magic == MH_MAGIC) || - (((struct mach_header *)handle)->magic == MH_CIGAM)) - { - error(0, "Can't remove dynamic libraries on darwin"); - return 0; - } - if (!NSUnLinkModule(handle, 0)) - { - error(0, "unable to unlink module %s", NSNameOfModule(handle)); - return 1; - } - return 0; + if ((((struct mach_header *)handle)->magic == MH_MAGIC) || + (((struct mach_header *)handle)->magic == MH_CIGAM)) + { + error(0, "Can't remove dynamic libraries on darwin"); + return 0; + } + if (!NSUnLinkModule(handle, 0)) + { + error(0, "unable to unlink module %s", NSNameOfModule(handle)); + return 1; + } + return 0; } /* dlsym, prepend the underscore and call dlsymIntern */ static void *darwin_dlsym(void *handle, const char *symbol) { - static char undersym[257]; /* Saves calls to malloc(3) */ - int sym_len = strlen(symbol); - void *value = NULL; - char *malloc_sym = NULL; + static char undersym[257]; /* Saves calls to malloc(3) */ + int sym_len = strlen(symbol); + void *value = NULL; + char *malloc_sym = NULL; - if (sym_len < 256) - { - snprintf(undersym, 256, "_%s", symbol); - value = dlsymIntern(handle, undersym); - } - else - { - malloc_sym = malloc(sym_len + 2); - if (malloc_sym) - { - sprintf(malloc_sym, "_%s", symbol); - value = dlsymIntern(handle, malloc_sym); - free(malloc_sym); - } - else - { - error(0, "Unable to allocate memory"); - } - } - return value; + if (sym_len < 256) + { + snprintf(undersym, 256, "_%s", symbol); + value = dlsymIntern(handle, undersym); + } + else + { + malloc_sym = malloc(sym_len + 2); + if (malloc_sym) + { + sprintf(malloc_sym, "_%s", symbol); + value = dlsymIntern(handle, malloc_sym); + free(malloc_sym); + } + else + { + error(0, "Unable to allocate memory"); + } + } + return value; } static int darwin_dladdr(const void *handle, Dl_info *info) { - return 0; + return 0; } #endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */ @@ -252,21 +252,21 @@ static void __attribute__ ((constructor)) ctypes_dlfcn_init(void); static #endif void ctypes_dlfcn_init(void) { - if (dlopen != NULL) { - ctypes_dlsym = dlsym; - ctypes_dlopen = dlopen; - ctypes_dlerror = dlerror; - ctypes_dlclose = dlclose; - ctypes_dladdr = dladdr; - } else { + if (dlopen != NULL) { + ctypes_dlsym = dlsym; + ctypes_dlopen = dlopen; + ctypes_dlerror = dlerror; + ctypes_dlclose = dlclose; + ctypes_dladdr = dladdr; + } else { #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 - ctypes_dlsym = darwin_dlsym; - ctypes_dlopen = darwin_dlopen; - ctypes_dlerror = darwin_dlerror; - ctypes_dlclose = darwin_dlclose; - ctypes_dladdr = darwin_dladdr; + ctypes_dlsym = darwin_dlsym; + ctypes_dlopen = darwin_dlopen; + ctypes_dlerror = darwin_dlerror; + ctypes_dlclose = darwin_dlclose; + ctypes_dladdr = darwin_dladdr; #endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */ - } + } } #endif /* CTYPES_DARWIN_DLFCN */ diff --git a/Modules/_ctypes/malloc_closure.c b/Modules/_ctypes/malloc_closure.c index 9a5bfcf..ae857a2 100644 --- a/Modules/_ctypes/malloc_closure.c +++ b/Modules/_ctypes/malloc_closure.c @@ -23,8 +23,8 @@ /******************************************************************/ typedef union _tagITEM { - ffi_closure closure; - union _tagITEM *next; + ffi_closure closure; + union _tagITEM *next; } ITEM; static ITEM *free_list; @@ -32,58 +32,58 @@ static int _pagesize; static void more_core(void) { - ITEM *item; - int count, i; + ITEM *item; + int count, i; /* determine the pagesize */ #ifdef MS_WIN32 - if (!_pagesize) { - SYSTEM_INFO systeminfo; - GetSystemInfo(&systeminfo); - _pagesize = systeminfo.dwPageSize; - } + if (!_pagesize) { + SYSTEM_INFO systeminfo; + GetSystemInfo(&systeminfo); + _pagesize = systeminfo.dwPageSize; + } #else - if (!_pagesize) { + if (!_pagesize) { #ifdef _SC_PAGESIZE - _pagesize = sysconf(_SC_PAGESIZE); + _pagesize = sysconf(_SC_PAGESIZE); #else - _pagesize = getpagesize(); + _pagesize = getpagesize(); #endif - } + } #endif - /* calculate the number of nodes to allocate */ - count = BLOCKSIZE / sizeof(ITEM); + /* calculate the number of nodes to allocate */ + count = BLOCKSIZE / sizeof(ITEM); - /* allocate a memory block */ + /* allocate a memory block */ #ifdef MS_WIN32 - item = (ITEM *)VirtualAlloc(NULL, - count * sizeof(ITEM), - MEM_COMMIT, - PAGE_EXECUTE_READWRITE); - if (item == NULL) - return; + item = (ITEM *)VirtualAlloc(NULL, + count * sizeof(ITEM), + MEM_COMMIT, + PAGE_EXECUTE_READWRITE); + if (item == NULL) + return; #else - item = (ITEM *)mmap(NULL, - count * sizeof(ITEM), - PROT_READ | PROT_WRITE | PROT_EXEC, - MAP_PRIVATE | MAP_ANONYMOUS, - -1, - 0); - if (item == (void *)MAP_FAILED) - return; + item = (ITEM *)mmap(NULL, + count * sizeof(ITEM), + PROT_READ | PROT_WRITE | PROT_EXEC, + MAP_PRIVATE | MAP_ANONYMOUS, + -1, + 0); + if (item == (void *)MAP_FAILED) + return; #endif #ifdef MALLOC_CLOSURE_DEBUG - printf("block at %p allocated (%d bytes), %d ITEMs\n", - item, count * sizeof(ITEM), count); + printf("block at %p allocated (%d bytes), %d ITEMs\n", + item, count * sizeof(ITEM), count); #endif - /* put them into the free list */ - for (i = 0; i < count; ++i) { - item->next = free_list; - free_list = item; - ++item; - } + /* put them into the free list */ + for (i = 0; i < count; ++i) { + item->next = free_list; + free_list = item; + ++item; + } } /******************************************************************/ @@ -91,20 +91,20 @@ static void more_core(void) /* put the item back into the free list */ void _ctypes_free_closure(void *p) { - ITEM *item = (ITEM *)p; - item->next = free_list; - free_list = item; + ITEM *item = (ITEM *)p; + item->next = free_list; + free_list = item; } /* return one item from the free list, allocating more if needed */ void *_ctypes_alloc_closure(void) { - ITEM *item; - if (!free_list) - more_core(); - if (!free_list) - return NULL; - item = free_list; - free_list = item->next; - return item; + ITEM *item; + if (!free_list) + more_core(); + if (!free_list) + return NULL; + item = free_list; + free_list = item->next; + return item; } diff --git a/Modules/_ctypes/stgdict.c b/Modules/_ctypes/stgdict.c index 6c81017..105e0df 100644 --- a/Modules/_ctypes/stgdict.c +++ b/Modules/_ctypes/stgdict.c @@ -19,143 +19,143 @@ static int PyCStgDict_init(StgDictObject *self, PyObject *args, PyObject *kwds) { - if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) - return -1; - self->format = NULL; - self->ndim = 0; - self->shape = NULL; - return 0; + if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) + return -1; + self->format = NULL; + self->ndim = 0; + self->shape = NULL; + return 0; } static int PyCStgDict_clear(StgDictObject *self) { - Py_CLEAR(self->proto); - Py_CLEAR(self->argtypes); - Py_CLEAR(self->converters); - Py_CLEAR(self->restype); - Py_CLEAR(self->checker); - return 0; + Py_CLEAR(self->proto); + Py_CLEAR(self->argtypes); + Py_CLEAR(self->converters); + Py_CLEAR(self->restype); + Py_CLEAR(self->checker); + return 0; } static void PyCStgDict_dealloc(StgDictObject *self) { - PyCStgDict_clear(self); - PyMem_Free(self->format); - PyMem_Free(self->shape); - PyMem_Free(self->ffi_type_pointer.elements); - PyDict_Type.tp_dealloc((PyObject *)self); + PyCStgDict_clear(self); + PyMem_Free(self->format); + PyMem_Free(self->shape); + PyMem_Free(self->ffi_type_pointer.elements); + PyDict_Type.tp_dealloc((PyObject *)self); } int PyCStgDict_clone(StgDictObject *dst, StgDictObject *src) { - char *d, *s; - Py_ssize_t size; - - PyCStgDict_clear(dst); - PyMem_Free(dst->ffi_type_pointer.elements); - PyMem_Free(dst->format); - dst->format = NULL; - PyMem_Free(dst->shape); - dst->shape = NULL; - dst->ffi_type_pointer.elements = NULL; - - d = (char *)dst; - s = (char *)src; - memcpy(d + sizeof(PyDictObject), - s + sizeof(PyDictObject), - sizeof(StgDictObject) - sizeof(PyDictObject)); - - Py_XINCREF(dst->proto); - Py_XINCREF(dst->argtypes); - Py_XINCREF(dst->converters); - Py_XINCREF(dst->restype); - Py_XINCREF(dst->checker); - - if (src->format) { - dst->format = PyMem_Malloc(strlen(src->format) + 1); - if (dst->format == NULL) - return -1; - strcpy(dst->format, src->format); - } - if (src->shape) { - dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim); - if (dst->shape == NULL) - return -1; - memcpy(dst->shape, src->shape, - sizeof(Py_ssize_t) * src->ndim); - } - - if (src->ffi_type_pointer.elements == NULL) - return 0; - size = sizeof(ffi_type *) * (src->length + 1); - dst->ffi_type_pointer.elements = PyMem_Malloc(size); - if (dst->ffi_type_pointer.elements == NULL) { - PyErr_NoMemory(); - return -1; - } - memcpy(dst->ffi_type_pointer.elements, - src->ffi_type_pointer.elements, - size); - return 0; + char *d, *s; + Py_ssize_t size; + + PyCStgDict_clear(dst); + PyMem_Free(dst->ffi_type_pointer.elements); + PyMem_Free(dst->format); + dst->format = NULL; + PyMem_Free(dst->shape); + dst->shape = NULL; + dst->ffi_type_pointer.elements = NULL; + + d = (char *)dst; + s = (char *)src; + memcpy(d + sizeof(PyDictObject), + s + sizeof(PyDictObject), + sizeof(StgDictObject) - sizeof(PyDictObject)); + + Py_XINCREF(dst->proto); + Py_XINCREF(dst->argtypes); + Py_XINCREF(dst->converters); + Py_XINCREF(dst->restype); + Py_XINCREF(dst->checker); + + if (src->format) { + dst->format = PyMem_Malloc(strlen(src->format) + 1); + if (dst->format == NULL) + return -1; + strcpy(dst->format, src->format); + } + if (src->shape) { + dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim); + if (dst->shape == NULL) + return -1; + memcpy(dst->shape, src->shape, + sizeof(Py_ssize_t) * src->ndim); + } + + if (src->ffi_type_pointer.elements == NULL) + return 0; + size = sizeof(ffi_type *) * (src->length + 1); + dst->ffi_type_pointer.elements = PyMem_Malloc(size); + if (dst->ffi_type_pointer.elements == NULL) { + PyErr_NoMemory(); + return -1; + } + memcpy(dst->ffi_type_pointer.elements, + src->ffi_type_pointer.elements, + size); + return 0; } PyTypeObject PyCStgDict_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "StgDict", - sizeof(StgDictObject), - 0, - (destructor)PyCStgDict_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)PyCStgDict_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "StgDict", + sizeof(StgDictObject), + 0, + (destructor)PyCStgDict_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)PyCStgDict_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; /* May return NULL, but does not set an exception! */ StgDictObject * PyType_stgdict(PyObject *obj) { - PyTypeObject *type; - - if (!PyType_Check(obj)) - return NULL; - type = (PyTypeObject *)obj; - if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) - return NULL; - return (StgDictObject *)type->tp_dict; + PyTypeObject *type; + + if (!PyType_Check(obj)) + return NULL; + type = (PyTypeObject *)obj; + if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) + return NULL; + return (StgDictObject *)type->tp_dict; } /* May return NULL, but does not set an exception! */ @@ -166,10 +166,10 @@ PyType_stgdict(PyObject *obj) StgDictObject * PyObject_stgdict(PyObject *self) { - PyTypeObject *type = self->ob_type; - if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) - return NULL; - return (StgDictObject *)type->tp_dict; + PyTypeObject *type = self->ob_type; + if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) + return NULL; + return (StgDictObject *)type->tp_dict; } /* descr is the descriptor for a field marked as anonymous. Get all the @@ -178,78 +178,78 @@ PyObject_stgdict(PyObject *self) */ static int MakeFields(PyObject *type, CFieldObject *descr, - Py_ssize_t index, Py_ssize_t offset) + Py_ssize_t index, Py_ssize_t offset) { - Py_ssize_t i; - PyObject *fields; - PyObject *fieldlist; - - fields = PyObject_GetAttrString(descr->proto, "_fields_"); - if (fields == NULL) - return -1; - fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence"); - Py_DECREF(fields); - if (fieldlist == NULL) - return -1; - - for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) { - PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */ - PyObject *fname, *ftype, *bits; - CFieldObject *fdescr; - CFieldObject *new_descr; - /* Convert to PyArg_UnpackTuple... */ - if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) { - Py_DECREF(fieldlist); - return -1; - } - fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname); - if (fdescr == NULL) { - Py_DECREF(fieldlist); - return -1; - } - if (Py_TYPE(fdescr) != &PyCField_Type) { - PyErr_SetString(PyExc_TypeError, "unexpected type"); - Py_DECREF(fdescr); - Py_DECREF(fieldlist); - return -1; - } - if (fdescr->anonymous) { - int rc = MakeFields(type, fdescr, - index + fdescr->index, - offset + fdescr->offset); - Py_DECREF(fdescr); - if (rc == -1) { - Py_DECREF(fieldlist); - return -1; - } - continue; - } - new_descr = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, NULL); - if (new_descr == NULL) { - Py_DECREF(fdescr); - Py_DECREF(fieldlist); - return -1; - } - assert(Py_TYPE(new_descr) == &PyCField_Type); - new_descr->size = fdescr->size; - new_descr->offset = fdescr->offset + offset; - new_descr->index = fdescr->index + index; - new_descr->proto = fdescr->proto; - Py_XINCREF(new_descr->proto); - new_descr->getfunc = fdescr->getfunc; - new_descr->setfunc = fdescr->setfunc; - - Py_DECREF(fdescr); - - if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) { - Py_DECREF(fieldlist); - Py_DECREF(new_descr); - return -1; - } - Py_DECREF(new_descr); - } - Py_DECREF(fieldlist); - return 0; + Py_ssize_t i; + PyObject *fields; + PyObject *fieldlist; + + fields = PyObject_GetAttrString(descr->proto, "_fields_"); + if (fields == NULL) + return -1; + fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence"); + Py_DECREF(fields); + if (fieldlist == NULL) + return -1; + + for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) { + PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */ + PyObject *fname, *ftype, *bits; + CFieldObject *fdescr; + CFieldObject *new_descr; + /* Convert to PyArg_UnpackTuple... */ + if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) { + Py_DECREF(fieldlist); + return -1; + } + fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname); + if (fdescr == NULL) { + Py_DECREF(fieldlist); + return -1; + } + if (Py_TYPE(fdescr) != &PyCField_Type) { + PyErr_SetString(PyExc_TypeError, "unexpected type"); + Py_DECREF(fdescr); + Py_DECREF(fieldlist); + return -1; + } + if (fdescr->anonymous) { + int rc = MakeFields(type, fdescr, + index + fdescr->index, + offset + fdescr->offset); + Py_DECREF(fdescr); + if (rc == -1) { + Py_DECREF(fieldlist); + return -1; + } + continue; + } + new_descr = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, NULL); + if (new_descr == NULL) { + Py_DECREF(fdescr); + Py_DECREF(fieldlist); + return -1; + } + assert(Py_TYPE(new_descr) == &PyCField_Type); + new_descr->size = fdescr->size; + new_descr->offset = fdescr->offset + offset; + new_descr->index = fdescr->index + index; + new_descr->proto = fdescr->proto; + Py_XINCREF(new_descr->proto); + new_descr->getfunc = fdescr->getfunc; + new_descr->setfunc = fdescr->setfunc; + + Py_DECREF(fdescr); + + if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) { + Py_DECREF(fieldlist); + Py_DECREF(new_descr); + return -1; + } + Py_DECREF(new_descr); + } + Py_DECREF(fieldlist); + return 0; } /* Iterate over the names in the type's _anonymous_ attribute, if present, @@ -257,43 +257,43 @@ MakeFields(PyObject *type, CFieldObject *descr, static int MakeAnonFields(PyObject *type) { - PyObject *anon; - PyObject *anon_names; - Py_ssize_t i; - - anon = PyObject_GetAttrString(type, "_anonymous_"); - if (anon == NULL) { - PyErr_Clear(); - return 0; - } - anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence"); - Py_DECREF(anon); - if (anon_names == NULL) - return -1; - - for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) { - PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */ - CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname); - if (descr == NULL) { - Py_DECREF(anon_names); - return -1; - } - assert(Py_TYPE(descr) == &PyCField_Type); - descr->anonymous = 1; - - /* descr is in the field descriptor. */ - if (-1 == MakeFields(type, (CFieldObject *)descr, - ((CFieldObject *)descr)->index, - ((CFieldObject *)descr)->offset)) { - Py_DECREF(descr); - Py_DECREF(anon_names); - return -1; - } - Py_DECREF(descr); - } - - Py_DECREF(anon_names); - return 0; + PyObject *anon; + PyObject *anon_names; + Py_ssize_t i; + + anon = PyObject_GetAttrString(type, "_anonymous_"); + if (anon == NULL) { + PyErr_Clear(); + return 0; + } + anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence"); + Py_DECREF(anon); + if (anon_names == NULL) + return -1; + + for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) { + PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */ + CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname); + if (descr == NULL) { + Py_DECREF(anon_names); + return -1; + } + assert(Py_TYPE(descr) == &PyCField_Type); + descr->anonymous = 1; + + /* descr is in the field descriptor. */ + if (-1 == MakeFields(type, (CFieldObject *)descr, + ((CFieldObject *)descr)->index, + ((CFieldObject *)descr)->offset)) { + Py_DECREF(descr); + Py_DECREF(anon_names); + return -1; + } + Py_DECREF(descr); + } + + Py_DECREF(anon_names); + return 0; } /* @@ -303,261 +303,261 @@ MakeAnonFields(PyObject *type) int PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct) { - StgDictObject *stgdict, *basedict; - Py_ssize_t len, offset, size, align, i; - Py_ssize_t union_size, total_align; - Py_ssize_t field_size = 0; - int bitofs; - PyObject *isPacked; - int pack = 0; - Py_ssize_t ffi_ofs; - int big_endian; - - /* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to - be a way to use the old, broken sematics: _fields_ are not extended - but replaced in subclasses. - - XXX Remove this in ctypes 1.0! - */ - int use_broken_old_ctypes_semantics; - - if (fields == NULL) - return 0; + StgDictObject *stgdict, *basedict; + Py_ssize_t len, offset, size, align, i; + Py_ssize_t union_size, total_align; + Py_ssize_t field_size = 0; + int bitofs; + PyObject *isPacked; + int pack = 0; + Py_ssize_t ffi_ofs; + int big_endian; + + /* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to + be a way to use the old, broken sematics: _fields_ are not extended + but replaced in subclasses. + + XXX Remove this in ctypes 1.0! + */ + int use_broken_old_ctypes_semantics; + + if (fields == NULL) + return 0; #ifdef WORDS_BIGENDIAN - big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1; + big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1; #else - big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0; + big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0; #endif - use_broken_old_ctypes_semantics = \ - PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_"); - - isPacked = PyObject_GetAttrString(type, "_pack_"); - if (isPacked) { - pack = PyLong_AsLong(isPacked); - if (pack < 0 || PyErr_Occurred()) { - Py_XDECREF(isPacked); - PyErr_SetString(PyExc_ValueError, - "_pack_ must be a non-negative integer"); - return -1; - } - Py_DECREF(isPacked); - } else - PyErr_Clear(); - - len = PySequence_Length(fields); - if (len == -1) { - PyErr_SetString(PyExc_TypeError, - "'_fields_' must be a sequence of pairs"); - return -1; - } - - stgdict = PyType_stgdict(type); - if (!stgdict) - return -1; - /* If this structure/union is already marked final we cannot assign - _fields_ anymore. */ - - if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */ - PyErr_SetString(PyExc_AttributeError, - "_fields_ is final"); - return -1; - } - - if (stgdict->format) { - PyMem_Free(stgdict->format); - stgdict->format = NULL; - } - - if (stgdict->ffi_type_pointer.elements) - PyMem_Free(stgdict->ffi_type_pointer.elements); - - basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base); - if (basedict && !use_broken_old_ctypes_semantics) { - size = offset = basedict->size; - align = basedict->align; - union_size = 0; - total_align = align ? align : 1; - stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; - stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1)); - if (stgdict->ffi_type_pointer.elements == NULL) { - PyErr_NoMemory(); - return -1; - } - memset(stgdict->ffi_type_pointer.elements, 0, - sizeof(ffi_type *) * (basedict->length + len + 1)); - memcpy(stgdict->ffi_type_pointer.elements, - basedict->ffi_type_pointer.elements, - sizeof(ffi_type *) * (basedict->length)); - ffi_ofs = basedict->length; - } else { - offset = 0; - size = 0; - align = 0; - union_size = 0; - total_align = 1; - stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; - stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1)); - if (stgdict->ffi_type_pointer.elements == NULL) { - PyErr_NoMemory(); - return -1; - } - memset(stgdict->ffi_type_pointer.elements, 0, - sizeof(ffi_type *) * (len + 1)); - ffi_ofs = 0; - } - - assert(stgdict->format == NULL); - if (isStruct && !isPacked) { - stgdict->format = _ctypes_alloc_format_string(NULL, "T{"); - } else { - /* PEP3118 doesn't support union, or packed structures (well, - only standard packing, but we dont support the pep for - that). Use 'B' for bytes. */ - stgdict->format = _ctypes_alloc_format_string(NULL, "B"); - } + use_broken_old_ctypes_semantics = \ + PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_"); + + isPacked = PyObject_GetAttrString(type, "_pack_"); + if (isPacked) { + pack = PyLong_AsLong(isPacked); + if (pack < 0 || PyErr_Occurred()) { + Py_XDECREF(isPacked); + PyErr_SetString(PyExc_ValueError, + "_pack_ must be a non-negative integer"); + return -1; + } + Py_DECREF(isPacked); + } else + PyErr_Clear(); + + len = PySequence_Length(fields); + if (len == -1) { + PyErr_SetString(PyExc_TypeError, + "'_fields_' must be a sequence of pairs"); + return -1; + } + + stgdict = PyType_stgdict(type); + if (!stgdict) + return -1; + /* If this structure/union is already marked final we cannot assign + _fields_ anymore. */ + + if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */ + PyErr_SetString(PyExc_AttributeError, + "_fields_ is final"); + return -1; + } + + if (stgdict->format) { + PyMem_Free(stgdict->format); + stgdict->format = NULL; + } + + if (stgdict->ffi_type_pointer.elements) + PyMem_Free(stgdict->ffi_type_pointer.elements); + + basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base); + if (basedict && !use_broken_old_ctypes_semantics) { + size = offset = basedict->size; + align = basedict->align; + union_size = 0; + total_align = align ? align : 1; + stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; + stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1)); + if (stgdict->ffi_type_pointer.elements == NULL) { + PyErr_NoMemory(); + return -1; + } + memset(stgdict->ffi_type_pointer.elements, 0, + sizeof(ffi_type *) * (basedict->length + len + 1)); + memcpy(stgdict->ffi_type_pointer.elements, + basedict->ffi_type_pointer.elements, + sizeof(ffi_type *) * (basedict->length)); + ffi_ofs = basedict->length; + } else { + offset = 0; + size = 0; + align = 0; + union_size = 0; + total_align = 1; + stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; + stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1)); + if (stgdict->ffi_type_pointer.elements == NULL) { + PyErr_NoMemory(); + return -1; + } + memset(stgdict->ffi_type_pointer.elements, 0, + sizeof(ffi_type *) * (len + 1)); + ffi_ofs = 0; + } + + assert(stgdict->format == NULL); + if (isStruct && !isPacked) { + stgdict->format = _ctypes_alloc_format_string(NULL, "T{"); + } else { + /* PEP3118 doesn't support union, or packed structures (well, + only standard packing, but we dont support the pep for + that). Use 'B' for bytes. */ + stgdict->format = _ctypes_alloc_format_string(NULL, "B"); + } #define realdict ((PyObject *)&stgdict->dict) - for (i = 0; i < len; ++i) { - PyObject *name = NULL, *desc = NULL; - PyObject *pair = PySequence_GetItem(fields, i); - PyObject *prop; - StgDictObject *dict; - int bitsize = 0; - - if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) { - PyErr_SetString(PyExc_AttributeError, - "'_fields_' must be a sequence of pairs"); - Py_XDECREF(pair); - return -1; - } - dict = PyType_stgdict(desc); - if (dict == NULL) { - Py_DECREF(pair); - PyErr_Format(PyExc_TypeError, - "second item in _fields_ tuple (index %zd) must be a C type", - i); - return -1; - } - stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer; - if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) - stgdict->flags |= TYPEFLAG_HASPOINTER; - dict->flags |= DICTFLAG_FINAL; /* mark field type final */ - if (PyTuple_Size(pair) == 3) { /* bits specified */ - switch(dict->ffi_type_pointer.type) { - case FFI_TYPE_UINT8: - case FFI_TYPE_UINT16: - case FFI_TYPE_UINT32: - case FFI_TYPE_SINT64: - case FFI_TYPE_UINT64: - break; - - case FFI_TYPE_SINT8: - case FFI_TYPE_SINT16: - case FFI_TYPE_SINT32: - if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc + for (i = 0; i < len; ++i) { + PyObject *name = NULL, *desc = NULL; + PyObject *pair = PySequence_GetItem(fields, i); + PyObject *prop; + StgDictObject *dict; + int bitsize = 0; + + if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) { + PyErr_SetString(PyExc_AttributeError, + "'_fields_' must be a sequence of pairs"); + Py_XDECREF(pair); + return -1; + } + dict = PyType_stgdict(desc); + if (dict == NULL) { + Py_DECREF(pair); + PyErr_Format(PyExc_TypeError, + "second item in _fields_ tuple (index %zd) must be a C type", + i); + return -1; + } + stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer; + if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) + stgdict->flags |= TYPEFLAG_HASPOINTER; + dict->flags |= DICTFLAG_FINAL; /* mark field type final */ + if (PyTuple_Size(pair) == 3) { /* bits specified */ + switch(dict->ffi_type_pointer.type) { + case FFI_TYPE_UINT8: + case FFI_TYPE_UINT16: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + break; + + case FFI_TYPE_SINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_SINT32: + if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc #ifdef CTYPES_UNICODE - && dict->getfunc != _ctypes_get_fielddesc("u")->getfunc + && dict->getfunc != _ctypes_get_fielddesc("u")->getfunc #endif - ) - break; - /* else fall through */ - default: - PyErr_Format(PyExc_TypeError, - "bit fields not allowed for type %s", - ((PyTypeObject *)desc)->tp_name); - Py_DECREF(pair); - return -1; - } - if (bitsize <= 0 || bitsize > dict->size * 8) { - PyErr_SetString(PyExc_ValueError, - "number of bits invalid for bit field"); - Py_DECREF(pair); - return -1; - } - } else - bitsize = 0; - if (isStruct && !isPacked) { - char *fieldfmt = dict->format ? dict->format : "B"; - char *fieldname = _PyUnicode_AsString(name); - char *ptr; - Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt); - char *buf = alloca(len + 2 + 1); - - sprintf(buf, "%s:%s:", fieldfmt, fieldname); - - ptr = stgdict->format; - stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf); - PyMem_Free(ptr); - - if (stgdict->format == NULL) { - Py_DECREF(pair); - return -1; - } - } - if (isStruct) { - prop = PyCField_FromDesc(desc, i, - &field_size, bitsize, &bitofs, - &size, &offset, &align, - pack, big_endian); - } else /* union */ { - size = 0; - offset = 0; - align = 0; - prop = PyCField_FromDesc(desc, i, - &field_size, bitsize, &bitofs, - &size, &offset, &align, - pack, big_endian); - union_size = max(size, union_size); - } - total_align = max(align, total_align); - - if (!prop) { - Py_DECREF(pair); - return -1; - } - if (-1 == PyObject_SetAttr(type, name, prop)) { - Py_DECREF(prop); - Py_DECREF(pair); - return -1; - } - Py_DECREF(pair); - Py_DECREF(prop); - } + ) + break; + /* else fall through */ + default: + PyErr_Format(PyExc_TypeError, + "bit fields not allowed for type %s", + ((PyTypeObject *)desc)->tp_name); + Py_DECREF(pair); + return -1; + } + if (bitsize <= 0 || bitsize > dict->size * 8) { + PyErr_SetString(PyExc_ValueError, + "number of bits invalid for bit field"); + Py_DECREF(pair); + return -1; + } + } else + bitsize = 0; + if (isStruct && !isPacked) { + char *fieldfmt = dict->format ? dict->format : "B"; + char *fieldname = _PyUnicode_AsString(name); + char *ptr; + Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt); + char *buf = alloca(len + 2 + 1); + + sprintf(buf, "%s:%s:", fieldfmt, fieldname); + + ptr = stgdict->format; + stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf); + PyMem_Free(ptr); + + if (stgdict->format == NULL) { + Py_DECREF(pair); + return -1; + } + } + if (isStruct) { + prop = PyCField_FromDesc(desc, i, + &field_size, bitsize, &bitofs, + &size, &offset, &align, + pack, big_endian); + } else /* union */ { + size = 0; + offset = 0; + align = 0; + prop = PyCField_FromDesc(desc, i, + &field_size, bitsize, &bitofs, + &size, &offset, &align, + pack, big_endian); + union_size = max(size, union_size); + } + total_align = max(align, total_align); + + if (!prop) { + Py_DECREF(pair); + return -1; + } + if (-1 == PyObject_SetAttr(type, name, prop)) { + Py_DECREF(prop); + Py_DECREF(pair); + return -1; + } + Py_DECREF(pair); + Py_DECREF(prop); + } #undef realdict - if (isStruct && !isPacked) { - char *ptr = stgdict->format; - stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}"); - PyMem_Free(ptr); - if (stgdict->format == NULL) - return -1; - } - - if (!isStruct) - size = union_size; - - /* Adjust the size according to the alignment requirements */ - size = ((size + total_align - 1) / total_align) * total_align; - - stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align, - Py_ssize_t, - unsigned short); - stgdict->ffi_type_pointer.size = size; - - stgdict->size = size; - stgdict->align = total_align; - stgdict->length = len; /* ADD ffi_ofs? */ - - /* We did check that this flag was NOT set above, it must not - have been set until now. */ - if (stgdict->flags & DICTFLAG_FINAL) { - PyErr_SetString(PyExc_AttributeError, - "Structure or union cannot contain itself"); - return -1; - } - stgdict->flags |= DICTFLAG_FINAL; - - return MakeAnonFields(type); + if (isStruct && !isPacked) { + char *ptr = stgdict->format; + stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}"); + PyMem_Free(ptr); + if (stgdict->format == NULL) + return -1; + } + + if (!isStruct) + size = union_size; + + /* Adjust the size according to the alignment requirements */ + size = ((size + total_align - 1) / total_align) * total_align; + + stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align, + Py_ssize_t, + unsigned short); + stgdict->ffi_type_pointer.size = size; + + stgdict->size = size; + stgdict->align = total_align; + stgdict->length = len; /* ADD ffi_ofs? */ + + /* We did check that this flag was NOT set above, it must not + have been set until now. */ + if (stgdict->flags & DICTFLAG_FINAL) { + PyErr_SetString(PyExc_AttributeError, + "Structure or union cannot contain itself"); + return -1; + } + stgdict->flags |= DICTFLAG_FINAL; + + return MakeAnonFields(type); } |