PageRenderTime 43ms CodeModel.GetById 986ms app.highlight 3589ms RepoModel.GetById 343ms app.codeStats 2ms

/Modules/_ctypes/_ctypes.c

http://unladen-swallow.googlecode.com/
C | 5688 lines | 4503 code | 562 blank | 623 comment | 877 complexity | 7a1aa045f181b16031ab55b50d942c59 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1/*****************************************************************
   2  This file should be kept compatible with Python 2.3, see PEP 291.
   3 *****************************************************************/
   4
   5
   6/*
   7  ToDo:
   8
   9  Get rid of the checker (and also the converters) field in CFuncPtrObject and
  10  StgDictObject, and replace them by slot functions in StgDictObject.
  11
  12  think about a buffer-like object (memory? bytes?)
  13
  14  Should POINTER(c_char) and POINTER(c_wchar) have a .value property?
  15  What about c_char and c_wchar arrays then?
  16
  17  Add from_mmap, from_file, from_string metaclass methods.
  18
  19  Maybe we can get away with from_file (calls read) and with a from_buffer
  20  method?
  21
  22  And what about the to_mmap, to_file, to_str(?) methods?  They would clobber
  23  the namespace, probably. So, functions instead? And we already have memmove...
  24*/
  25
  26/*
  27
  28Name			methods, members, getsets
  29==============================================================================
  30
  31StructType_Type		__new__(), from_address(), __mul__(), from_param()
  32UnionType_Type		__new__(), from_address(), __mul__(), from_param()
  33PointerType_Type	__new__(), from_address(), __mul__(), from_param(), set_type()
  34ArrayType_Type		__new__(), from_address(), __mul__(), from_param()
  35SimpleType_Type		__new__(), from_address(), __mul__(), from_param()
  36
  37CData_Type
  38  Struct_Type		__new__(), __init__()
  39  Pointer_Type		__new__(), __init__(), _as_parameter_, contents
  40  Array_Type		__new__(), __init__(), _as_parameter_, __get/setitem__(), __len__()
  41  Simple_Type		__new__(), __init__(), _as_parameter_
  42
  43CField_Type
  44StgDict_Type
  45
  46==============================================================================
  47
  48class methods
  49-------------
  50
  51It has some similarity to the byref() construct compared to pointer()
  52from_address(addr)
  53	- construct an instance from a given memory block (sharing this memory block)
  54
  55from_param(obj)
  56	- typecheck and convert a Python object into a C function call parameter
  57	  the result may be an instance of the type, or an integer or tuple
  58	  (typecode, value[, obj])
  59
  60instance methods/properties
  61---------------------------
  62
  63_as_parameter_
  64	- convert self into a C function call parameter
  65	  This is either an integer, or a 3-tuple (typecode, value, obj)
  66
  67functions
  68---------
  69
  70sizeof(cdata)
  71	- return the number of bytes the buffer contains
  72
  73sizeof(ctype)
  74	- return the number of bytes the buffer of an instance would contain
  75
  76byref(cdata)
  77
  78addressof(cdata)
  79
  80pointer(cdata)
  81
  82POINTER(ctype)
  83
  84bytes(cdata)
  85	- return the buffer contents as a sequence of bytes (which is currently a string)
  86
  87*/
  88
  89/*
  90 * StgDict_Type
  91 * StructType_Type
  92 * UnionType_Type
  93 * PointerType_Type
  94 * ArrayType_Type
  95 * SimpleType_Type
  96 *
  97 * CData_Type
  98 * Struct_Type
  99 * Union_Type
 100 * Array_Type
 101 * Simple_Type
 102 * Pointer_Type
 103 * CField_Type
 104 *
 105 */
 106
 107#define PY_SSIZE_T_CLEAN
 108
 109#include "Python.h"
 110#include "structmember.h"
 111
 112#include <ffi.h>
 113#ifdef MS_WIN32
 114#include <windows.h>
 115#include <malloc.h>
 116#ifndef IS_INTRESOURCE
 117#define IS_INTRESOURCE(x) (((size_t)(x) >> 16) == 0)
 118#endif
 119# ifdef _WIN32_WCE
 120/* Unlike desktop Windows, WinCE has both W and A variants of
 121   GetProcAddress, but the default W version is not what we want */
 122#  undef GetProcAddress
 123#  define GetProcAddress GetProcAddressA
 124# endif
 125#else
 126#include "ctypes_dlfcn.h"
 127#endif
 128#include "ctypes.h"
 129
 130PyObject *PyExc_ArgError;
 131
 132/* This dict maps ctypes types to POINTER types */
 133PyObject *_pointer_type_cache;
 134
 135static PyTypeObject Simple_Type;
 136
 137/* a callable object used for unpickling */
 138static PyObject *_unpickle;
 139
 140char *conversion_mode_encoding = NULL;
 141char *conversion_mode_errors = NULL;
 142
 143
 144/****************************************************************/
 145
 146#if (PY_VERSION_HEX < 0x02040000)
 147/* Only in Python 2.4 and up */
 148static PyObject *
 149PyTuple_Pack(int n, ...)
 150{
 151	int i;
 152	PyObject *o;
 153	PyObject *result;
 154	PyObject **items;
 155	va_list vargs;
 156
 157	va_start(vargs, n);
 158	result = PyTuple_New(n);
 159	if (result == NULL)
 160		return NULL;
 161	items = ((PyTupleObject *)result)->ob_item;
 162	for (i = 0; i < n; i++) {
 163		o = va_arg(vargs, PyObject *);
 164		Py_INCREF(o);
 165		items[i] = o;
 166	}
 167	va_end(vargs);
 168	return result;
 169}
 170#endif
 171
 172/****************************************************************/
 173
 174typedef struct {
 175	PyObject_HEAD
 176	PyObject *key;
 177	PyObject *dict;
 178} DictRemoverObject;
 179
 180static void
 181_DictRemover_dealloc(PyObject *_self)
 182{
 183	DictRemoverObject *self = (DictRemoverObject *)_self;
 184	Py_XDECREF(self->key);
 185	Py_XDECREF(self->dict);
 186	Py_TYPE(self)->tp_free(_self);
 187}
 188
 189static PyObject *
 190_DictRemover_call(PyObject *_self, PyObject *args, PyObject *kw)
 191{
 192	DictRemoverObject *self = (DictRemoverObject *)_self;
 193	if (self->key && self->dict) {
 194		if (-1 == PyDict_DelItem(self->dict, self->key))
 195			/* XXX Error context */
 196			PyErr_WriteUnraisable(Py_None);
 197		Py_DECREF(self->key);
 198		self->key = NULL;
 199		Py_DECREF(self->dict);
 200		self->dict = NULL;
 201	}
 202	Py_INCREF(Py_None);
 203	return Py_None;
 204}
 205
 206static PyTypeObject DictRemover_Type = {
 207	PyVarObject_HEAD_INIT(NULL, 0)
 208	"_ctypes.DictRemover",			/* tp_name */
 209	sizeof(DictRemoverObject),		/* tp_basicsize */
 210	0,					/* tp_itemsize */
 211	_DictRemover_dealloc,			/* tp_dealloc */
 212	0,					/* tp_print */
 213	0,					/* tp_getattr */
 214	0,					/* tp_setattr */
 215	0,					/* tp_compare */
 216	0,			       		/* tp_repr */
 217	0,					/* tp_as_number */
 218	0,					/* tp_as_sequence */
 219	0,					/* tp_as_mapping */
 220	0,					/* tp_hash */
 221	_DictRemover_call,			/* tp_call */
 222	0,					/* tp_str */
 223	0,					/* tp_getattro */
 224	0,					/* tp_setattro */
 225	0,					/* tp_as_buffer */
 226/* XXX should participate in GC? */
 227	Py_TPFLAGS_DEFAULT,			/* tp_flags */
 228	"deletes a key from a dictionary",	/* tp_doc */
 229	0,					/* tp_traverse */
 230	0,					/* tp_clear */
 231	0,					/* tp_richcompare */
 232	0,					/* tp_weaklistoffset */
 233	0,					/* tp_iter */
 234	0,					/* tp_iternext */
 235	0,					/* tp_methods */
 236	0,					/* tp_members */
 237	0,					/* tp_getset */
 238	0,					/* tp_base */
 239	0,					/* tp_dict */
 240	0,					/* tp_descr_get */
 241	0,					/* tp_descr_set */
 242	0,					/* tp_dictoffset */
 243	0,					/* tp_init */
 244	0,					/* tp_alloc */
 245	0,					/* tp_new */
 246	0,					/* tp_free */
 247};
 248
 249int
 250PyDict_SetItemProxy(PyObject *dict, PyObject *key, PyObject *item)
 251{
 252	PyObject *obj;
 253	DictRemoverObject *remover;
 254	PyObject *proxy;
 255	int result;
 256
 257	obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL);
 258	if (obj == NULL)
 259		return -1;
 260
 261	remover = (DictRemoverObject *)obj;
 262	assert(remover->key == NULL);
 263	assert(remover->dict == NULL);
 264	Py_INCREF(key);
 265	remover->key = key;
 266	Py_INCREF(dict);
 267	remover->dict = dict;
 268
 269	proxy = PyWeakref_NewProxy(item, obj);
 270	Py_DECREF(obj);
 271	if (proxy == NULL)
 272		return -1;
 273
 274	result = PyDict_SetItem(dict, key, proxy);
 275	Py_DECREF(proxy);
 276	return result;
 277}
 278
 279PyObject *
 280PyDict_GetItemProxy(PyObject *dict, PyObject *key)
 281{
 282	PyObject *result;
 283	PyObject *item = PyDict_GetItem(dict, key);
 284
 285	if (item == NULL)
 286		return NULL;
 287	if (!PyWeakref_CheckProxy(item))
 288		return item;
 289	result = PyWeakref_GET_OBJECT(item);
 290	if (result == Py_None)
 291		return NULL;
 292	return result;
 293}
 294
 295/******************************************************************/
 296/*
 297  Allocate a memory block for a pep3118 format string, copy prefix (if
 298  non-null) and suffix into it.  Returns NULL on failure, with the error
 299  indicator set.  If called with a suffix of NULL the error indicator must
 300  already be set.
 301 */
 302char *
 303alloc_format_string(const char *prefix, const char *suffix)
 304{
 305	size_t len;
 306	char *result;
 307
 308	if (suffix == NULL) {
 309		assert(PyErr_Occurred());
 310		return NULL;
 311	}
 312	len = strlen(suffix);
 313	if (prefix)
 314		len += strlen(prefix);
 315	result = PyMem_Malloc(len + 1);
 316	if (result == NULL)
 317		return NULL;
 318	if (prefix)
 319		strcpy(result, prefix);
 320	else
 321		result[0] = '\0';
 322	strcat(result, suffix);
 323	return result;
 324}
 325
 326/*
 327  StructType_Type - a meta type/class.  Creating a new class using this one as
 328  __metaclass__ will call the contructor StructUnionType_new.  It replaces the
 329  tp_dict member with a new instance of StgDict, and initializes the C
 330  accessible fields somehow.
 331*/
 332
 333static PyCArgObject *
 334StructUnionType_paramfunc(CDataObject *self)
 335{
 336	PyCArgObject *parg;
 337	StgDictObject *stgdict;
 338	
 339	parg = new_CArgObject();
 340	if (parg == NULL)
 341		return NULL;
 342
 343	parg->tag = 'V';
 344	stgdict = PyObject_stgdict((PyObject *)self);
 345	assert(stgdict); /* Cannot be NULL for structure/union instances */
 346	parg->pffi_type = &stgdict->ffi_type_pointer;
 347	/* For structure parameters (by value), parg->value doesn't contain the structure
 348	   data itself, instead parg->value.p *points* to the structure's data
 349	   See also _ctypes.c, function _call_function_pointer().
 350	*/
 351	parg->value.p = self->b_ptr;
 352	parg->size = self->b_size;
 353	Py_INCREF(self);
 354	parg->obj = (PyObject *)self;
 355	return parg;	
 356}
 357
 358static PyObject *
 359StructUnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds, int isStruct)
 360{
 361	PyTypeObject *result;
 362	PyObject *fields;
 363	StgDictObject *dict;
 364
 365	/* create the new instance (which is a class,
 366	   since we are a metatype!) */
 367	result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
 368	if (!result)
 369		return NULL;
 370
 371	/* keep this for bw compatibility */
 372	if (PyDict_GetItemString(result->tp_dict, "_abstract_"))
 373		return (PyObject *)result;
 374
 375	dict = (StgDictObject *)PyObject_CallObject((PyObject *)&StgDict_Type, NULL);
 376	if (!dict) {
 377		Py_DECREF(result);
 378		return NULL;
 379	}
 380	/* replace the class dict by our updated stgdict, which holds info
 381	   about storage requirements of the instances */
 382	if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) {
 383		Py_DECREF(result);
 384		Py_DECREF((PyObject *)dict);
 385		return NULL;
 386	}
 387	Py_DECREF(result->tp_dict);
 388	result->tp_dict = (PyObject *)dict;
 389	dict->format = alloc_format_string(NULL, "B");
 390	if (dict->format == NULL) {
 391		Py_DECREF(result);
 392		return NULL;
 393	}
 394
 395	dict->paramfunc = StructUnionType_paramfunc;
 396
 397	fields = PyDict_GetItemString((PyObject *)dict, "_fields_");
 398	if (!fields) {
 399		StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base);
 400
 401		if (basedict == NULL)
 402			return (PyObject *)result;
 403		/* copy base dict */
 404		if (-1 == StgDict_clone(dict, basedict)) {
 405			Py_DECREF(result);
 406			return NULL;
 407		}
 408		dict->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass dict */
 409		basedict->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass dict */
 410		return (PyObject *)result;
 411	}
 412
 413	if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) {
 414		Py_DECREF(result);
 415		return NULL;
 416	}
 417	return (PyObject *)result;
 418}
 419
 420static PyObject *
 421StructType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 422{
 423	return StructUnionType_new(type, args, kwds, 1);
 424}
 425
 426static PyObject *
 427UnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 428{
 429	return StructUnionType_new(type, args, kwds, 0);
 430}
 431
 432static char from_address_doc[] =
 433"C.from_address(integer) -> C instance\naccess a C instance at the specified address";
 434
 435static PyObject *
 436CDataType_from_address(PyObject *type, PyObject *value)
 437{
 438	void *buf;
 439	if (!PyInt_Check(value) && !PyLong_Check(value)) {
 440		PyErr_SetString(PyExc_TypeError,
 441				"integer expected");
 442		return NULL;
 443	}
 444	buf = (void *)PyLong_AsVoidPtr(value);
 445	if (PyErr_Occurred())
 446		return NULL;
 447	return CData_AtAddress(type, buf);
 448}
 449
 450static char from_buffer_doc[] =
 451"C.from_buffer(object, offset=0) -> C instance\ncreate a C instance from a writeable buffer";
 452
 453static int
 454KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep);
 455
 456static PyObject *
 457CDataType_from_buffer(PyObject *type, PyObject *args)
 458{
 459	void *buffer;
 460	Py_ssize_t buffer_len;
 461	Py_ssize_t offset = 0;
 462	PyObject *obj, *result;
 463	StgDictObject *dict = PyType_stgdict(type);
 464	assert (dict);
 465
 466	if (!PyArg_ParseTuple(args,
 467#if (PY_VERSION_HEX < 0x02050000)
 468			      "O|i:from_buffer",
 469#else
 470			      "O|n:from_buffer",
 471#endif
 472			      &obj, &offset))
 473		return NULL;
 474
 475	if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len))
 476		return NULL;
 477
 478	if (offset < 0) {
 479		PyErr_SetString(PyExc_ValueError,
 480				"offset cannot be negative");
 481		return NULL;
 482	}
 483	if (dict->size > buffer_len - offset) {
 484		PyErr_Format(PyExc_ValueError,
 485#if (PY_VERSION_HEX < 0x02050000)
 486			     "Buffer size too small (%d instead of at least %d bytes)",
 487#else
 488			     "Buffer size too small (%zd instead of at least %zd bytes)",
 489#endif
 490			     buffer_len, dict->size + offset);
 491		return NULL;
 492	}
 493
 494	result = CData_AtAddress(type, (char *)buffer + offset);
 495	if (result == NULL)
 496		return NULL;
 497
 498	Py_INCREF(obj);
 499	if (-1 == KeepRef((CDataObject *)result, -1, obj)) {
 500		Py_DECREF(result);
 501		return NULL;
 502	}
 503	return result;
 504}
 505
 506static char from_buffer_copy_doc[] =
 507"C.from_buffer_copy(object, offset=0) -> C instance\ncreate a C instance from a readable buffer";
 508
 509static PyObject *
 510GenericCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
 511
 512static PyObject *
 513CDataType_from_buffer_copy(PyObject *type, PyObject *args)
 514{
 515	const void *buffer;
 516	Py_ssize_t buffer_len;
 517	Py_ssize_t offset = 0;
 518	PyObject *obj, *result;
 519	StgDictObject *dict = PyType_stgdict(type);
 520	assert (dict);
 521
 522	if (!PyArg_ParseTuple(args,
 523#if (PY_VERSION_HEX < 0x02050000)
 524			      "O|i:from_buffer",
 525#else
 526			      "O|n:from_buffer",
 527#endif
 528			      &obj, &offset))
 529		return NULL;
 530
 531	if (-1 == PyObject_AsReadBuffer(obj, &buffer, &buffer_len))
 532		return NULL;
 533
 534	if (offset < 0) {
 535		PyErr_SetString(PyExc_ValueError,
 536				"offset cannot be negative");
 537		return NULL;
 538	}
 539
 540	if (dict->size > buffer_len - offset) {
 541		PyErr_Format(PyExc_ValueError,
 542#if (PY_VERSION_HEX < 0x02050000)
 543			     "Buffer size too small (%d instead of at least %d bytes)",
 544#else
 545			     "Buffer size too small (%zd instead of at least %zd bytes)",
 546#endif
 547			     buffer_len, dict->size + offset);
 548		return NULL;
 549	}
 550
 551	result = GenericCData_new((PyTypeObject *)type, NULL, NULL);
 552	if (result == NULL)
 553		return NULL;
 554	memcpy(((CDataObject *)result)->b_ptr,
 555	       (char *)buffer+offset, dict->size);
 556	return result;
 557}
 558
 559static char in_dll_doc[] =
 560"C.in_dll(dll, name) -> C instance\naccess a C instance in a dll";
 561
 562static PyObject *
 563CDataType_in_dll(PyObject *type, PyObject *args)
 564{
 565	PyObject *dll;
 566	char *name;
 567	PyObject *obj;
 568	void *handle;
 569	void *address;
 570
 571	if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name))
 572		return NULL;
 573
 574	obj = PyObject_GetAttrString(dll, "_handle");
 575	if (!obj)
 576		return NULL;
 577	if (!PyInt_Check(obj) && !PyLong_Check(obj)) {
 578		PyErr_SetString(PyExc_TypeError,
 579				"the _handle attribute of the second argument must be an integer");
 580		Py_DECREF(obj);
 581		return NULL;
 582	}
 583	handle = (void *)PyLong_AsVoidPtr(obj);
 584	Py_DECREF(obj);
 585	if (PyErr_Occurred()) {
 586		PyErr_SetString(PyExc_ValueError,
 587				"could not convert the _handle attribute to a pointer");
 588		return NULL;
 589	}
 590
 591#ifdef MS_WIN32
 592	address = (void *)GetProcAddress(handle, name);
 593	if (!address) {
 594		PyErr_Format(PyExc_ValueError,
 595			     "symbol '%s' not found",
 596			     name);
 597		return NULL;
 598	}
 599#else
 600	address = (void *)ctypes_dlsym(handle, name);
 601	if (!address) {
 602#ifdef __CYGWIN__
 603/* dlerror() isn't very helpful on cygwin */
 604		PyErr_Format(PyExc_ValueError,
 605			     "symbol '%s' not found (%s) ",
 606			     name);
 607#else
 608		PyErr_SetString(PyExc_ValueError, ctypes_dlerror());
 609#endif
 610		return NULL;
 611	}
 612#endif
 613	return CData_AtAddress(type, address);
 614}
 615
 616static char from_param_doc[] =
 617"Convert a Python object into a function call parameter.";
 618
 619static PyObject *
 620CDataType_from_param(PyObject *type, PyObject *value)
 621{
 622	PyObject *as_parameter;
 623	if (1 == PyObject_IsInstance(value, type)) {
 624		Py_INCREF(value);
 625		return value;
 626	}
 627	if (PyCArg_CheckExact(value)) {
 628		PyCArgObject *p = (PyCArgObject *)value;
 629		PyObject *ob = p->obj;
 630		const char *ob_name;
 631		StgDictObject *dict;
 632		dict = PyType_stgdict(type);
 633
 634		/* If we got a PyCArgObject, we must check if the object packed in it
 635		   is an instance of the type's dict->proto */
 636		if(dict && ob
 637		   && PyObject_IsInstance(ob, dict->proto)) {
 638			Py_INCREF(value);
 639			return value;
 640		}
 641		ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???";
 642		PyErr_Format(PyExc_TypeError,
 643			     "expected %s instance instead of pointer to %s",
 644			     ((PyTypeObject *)type)->tp_name, ob_name);
 645		return NULL;
 646	}
 647
 648	as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
 649	if (as_parameter) {
 650		value = CDataType_from_param(type, as_parameter);
 651		Py_DECREF(as_parameter);
 652		return value;
 653	}
 654	PyErr_Format(PyExc_TypeError,
 655		     "expected %s instance instead of %s",
 656		     ((PyTypeObject *)type)->tp_name,
 657		     Py_TYPE(value)->tp_name);
 658	return NULL;
 659}
 660
 661static PyMethodDef CDataType_methods[] = {
 662	{ "from_param", CDataType_from_param, METH_O, from_param_doc },
 663	{ "from_address", CDataType_from_address, METH_O, from_address_doc },
 664	{ "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
 665	{ "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
 666	{ "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc },
 667	{ NULL, NULL },
 668};
 669
 670static PyObject *
 671CDataType_repeat(PyObject *self, Py_ssize_t length)
 672{
 673	if (length < 0)
 674		return PyErr_Format(PyExc_ValueError,
 675#if (PY_VERSION_HEX < 0x02050000)
 676				    "Array length must be >= 0, not %d",
 677#else
 678				    "Array length must be >= 0, not %zd",
 679#endif
 680				    length);
 681	return CreateArrayType(self, length);
 682}
 683
 684static PySequenceMethods CDataType_as_sequence = {
 685	0,			/* inquiry sq_length; */
 686	0,			/* binaryfunc sq_concat; */
 687	CDataType_repeat,	/* intargfunc sq_repeat; */
 688	0,			/* intargfunc sq_item; */
 689	0,			/* intintargfunc sq_slice; */
 690	0,			/* intobjargproc sq_ass_item; */
 691	0,			/* intintobjargproc sq_ass_slice; */
 692	0,			/* objobjproc sq_contains; */
 693	
 694	0,			/* binaryfunc sq_inplace_concat; */
 695	0,			/* intargfunc sq_inplace_repeat; */
 696};
 697
 698static int
 699CDataType_clear(PyTypeObject *self)
 700{
 701	StgDictObject *dict = PyType_stgdict((PyObject *)self);
 702	if (dict)
 703		Py_CLEAR(dict->proto);
 704	return PyType_Type.tp_clear((PyObject *)self);
 705}
 706
 707static int
 708CDataType_traverse(PyTypeObject *self, visitproc visit, void *arg)
 709{
 710	StgDictObject *dict = PyType_stgdict((PyObject *)self);
 711	if (dict)
 712		Py_VISIT(dict->proto);
 713	return PyType_Type.tp_traverse((PyObject *)self, visit, arg);
 714}
 715
 716static int
 717StructType_setattro(PyObject *self, PyObject *key, PyObject *value)
 718{
 719	/* XXX Should we disallow deleting _fields_? */
 720	if (-1 == PyType_Type.tp_setattro(self, key, value))
 721		return -1;
 722	
 723	if (value && PyString_Check(key) &&
 724	    0 == strcmp(PyString_AS_STRING(key), "_fields_"))
 725		return StructUnionType_update_stgdict(self, value, 1);
 726	return 0;
 727}
 728
 729
 730static int
 731UnionType_setattro(PyObject *self, PyObject *key, PyObject *value)
 732{
 733	/* XXX Should we disallow deleting _fields_? */
 734	if (-1 == PyObject_GenericSetAttr(self, key, value))
 735		return -1;
 736	
 737	if (PyString_Check(key) &&
 738	    0 == strcmp(PyString_AS_STRING(key), "_fields_"))
 739		return StructUnionType_update_stgdict(self, value, 0);
 740	return 0;
 741}
 742
 743
 744PyTypeObject StructType_Type = {
 745	PyVarObject_HEAD_INIT(NULL, 0)
 746	"_ctypes.StructType",			/* tp_name */
 747	0,					/* tp_basicsize */
 748	0,					/* tp_itemsize */
 749	0,					/* tp_dealloc */
 750	0,					/* tp_print */
 751	0,					/* tp_getattr */
 752	0,					/* tp_setattr */
 753	0,					/* tp_compare */
 754	0,			       		/* tp_repr */
 755	0,					/* tp_as_number */
 756	&CDataType_as_sequence,			/* tp_as_sequence */
 757	0,					/* tp_as_mapping */
 758	0,					/* tp_hash */
 759	0,					/* tp_call */
 760	0,					/* tp_str */
 761	0,					/* tp_getattro */
 762	StructType_setattro,			/* tp_setattro */
 763	0,					/* tp_as_buffer */
 764	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
 765	"metatype for the CData Objects",	/* tp_doc */
 766	(traverseproc)CDataType_traverse,	/* tp_traverse */
 767	(inquiry)CDataType_clear,		/* tp_clear */
 768	0,					/* tp_richcompare */
 769	0,					/* tp_weaklistoffset */
 770	0,					/* tp_iter */
 771	0,					/* tp_iternext */
 772	CDataType_methods,			/* tp_methods */
 773	0,					/* tp_members */
 774	0,					/* tp_getset */
 775	0,					/* tp_base */
 776	0,					/* tp_dict */
 777	0,					/* tp_descr_get */
 778	0,					/* tp_descr_set */
 779	0,					/* tp_dictoffset */
 780	0,					/* tp_init */
 781	0,					/* tp_alloc */
 782	StructType_new,				/* tp_new */
 783	0,					/* tp_free */
 784};
 785
 786static PyTypeObject UnionType_Type = {
 787	PyVarObject_HEAD_INIT(NULL, 0)
 788	"_ctypes.UnionType",			/* tp_name */
 789	0,					/* tp_basicsize */
 790	0,					/* tp_itemsize */
 791	0,					/* tp_dealloc */
 792	0,					/* tp_print */
 793	0,					/* tp_getattr */
 794	0,					/* tp_setattr */
 795	0,					/* tp_compare */
 796	0,			       		/* tp_repr */
 797	0,					/* tp_as_number */
 798	&CDataType_as_sequence,		/* tp_as_sequence */
 799	0,					/* tp_as_mapping */
 800	0,					/* tp_hash */
 801	0,					/* tp_call */
 802	0,					/* tp_str */
 803	0,					/* tp_getattro */
 804	UnionType_setattro,			/* tp_setattro */
 805	0,					/* tp_as_buffer */
 806	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
 807	"metatype for the CData Objects",	/* tp_doc */
 808	(traverseproc)CDataType_traverse,	/* tp_traverse */
 809	(inquiry)CDataType_clear,		/* tp_clear */
 810	0,					/* tp_richcompare */
 811	0,					/* tp_weaklistoffset */
 812	0,					/* tp_iter */
 813	0,					/* tp_iternext */
 814	CDataType_methods,			/* tp_methods */
 815	0,					/* tp_members */
 816	0,					/* tp_getset */
 817	0,					/* tp_base */
 818	0,					/* tp_dict */
 819	0,					/* tp_descr_get */
 820	0,					/* tp_descr_set */
 821	0,					/* tp_dictoffset */
 822	0,					/* tp_init */
 823	0,					/* tp_alloc */
 824	UnionType_new,				/* tp_new */
 825	0,					/* tp_free */
 826};
 827
 828
 829/******************************************************************/
 830
 831/*
 832
 833The PointerType_Type metaclass must ensure that the subclass of Pointer can be
 834created. It must check for a _type_ attribute in the class. Since are no
 835runtime created properties, a CField is probably *not* needed ?
 836
 837class IntPointer(Pointer):
 838    _type_ = "i"
 839
 840The Pointer_Type provides the functionality: a contents method/property, a
 841size property/method, and the sequence protocol.
 842
 843*/
 844
 845static int
 846PointerType_SetProto(StgDictObject *stgdict, PyObject *proto)
 847{
 848	if (!proto || !PyType_Check(proto)) {
 849		PyErr_SetString(PyExc_TypeError,
 850				"_type_ must be a type");
 851		return -1;
 852	}
 853	if (!PyType_stgdict(proto)) {
 854		PyErr_SetString(PyExc_TypeError,
 855				"_type_ must have storage info");
 856		return -1;
 857	}
 858	Py_INCREF(proto);
 859	Py_XDECREF(stgdict->proto);
 860	stgdict->proto = proto;
 861	return 0;
 862}
 863
 864static PyCArgObject *
 865PointerType_paramfunc(CDataObject *self)
 866{
 867	PyCArgObject *parg;
 868
 869	parg = new_CArgObject();
 870	if (parg == NULL)
 871		return NULL;
 872
 873	parg->tag = 'P';
 874	parg->pffi_type = &ffi_type_pointer;
 875	Py_INCREF(self);
 876	parg->obj = (PyObject *)self;
 877	parg->value.p = *(void **)self->b_ptr;
 878	return parg;
 879}
 880
 881static PyObject *
 882PointerType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 883{
 884	PyTypeObject *result;
 885	StgDictObject *stgdict;
 886	PyObject *proto;
 887	PyObject *typedict;
 888
 889	typedict = PyTuple_GetItem(args, 2);
 890	if (!typedict)
 891		return NULL;
 892/*
 893  stgdict items size, align, length contain info about pointers itself,
 894  stgdict->proto has info about the pointed to type!
 895*/
 896	stgdict = (StgDictObject *)PyObject_CallObject(
 897		(PyObject *)&StgDict_Type, NULL);
 898	if (!stgdict)
 899		return NULL;
 900	stgdict->size = sizeof(void *);
 901	stgdict->align = getentry("P")->pffi_type->alignment;
 902	stgdict->length = 1;
 903	stgdict->ffi_type_pointer = ffi_type_pointer;
 904	stgdict->paramfunc = PointerType_paramfunc;
 905	stgdict->flags |= TYPEFLAG_ISPOINTER;
 906
 907	proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
 908	if (proto && -1 == PointerType_SetProto(stgdict, proto)) {
 909		Py_DECREF((PyObject *)stgdict);
 910		return NULL;
 911	}
 912
 913	if (proto) {
 914		StgDictObject *itemdict = PyType_stgdict(proto);
 915		assert(itemdict);
 916		/* If itemdict->format is NULL, then this is a pointer to an
 917		   incomplete type.  We create a generic format string
 918		   'pointer to bytes' in this case.  XXX Better would be to
 919		   fix the format string later...
 920		*/
 921		stgdict->format = alloc_format_string("&",
 922			      itemdict->format ? itemdict->format : "B");
 923		if (stgdict->format == NULL) {
 924			Py_DECREF((PyObject *)stgdict);
 925			return NULL;
 926		}
 927	}
 928
 929	/* create the new instance (which is a class,
 930	   since we are a metatype!) */
 931	result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
 932	if (result == NULL) {
 933		Py_DECREF((PyObject *)stgdict);
 934		return NULL;
 935	}
 936
 937	/* replace the class dict by our updated spam dict */
 938	if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
 939		Py_DECREF(result);
 940		Py_DECREF((PyObject *)stgdict);
 941		return NULL;
 942	}
 943	Py_DECREF(result->tp_dict);
 944	result->tp_dict = (PyObject *)stgdict;
 945
 946	return (PyObject *)result;
 947}
 948
 949
 950static PyObject *
 951PointerType_set_type(PyTypeObject *self, PyObject *type)
 952{
 953	StgDictObject *dict;
 954
 955	dict = PyType_stgdict((PyObject *)self);
 956	assert(dict);
 957
 958	if (-1 == PointerType_SetProto(dict, type))
 959		return NULL;
 960
 961	if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type))
 962		return NULL;
 963
 964	Py_INCREF(Py_None);
 965	return Py_None;
 966}
 967
 968staticforward PyObject *_byref(PyObject *);
 969
 970static PyObject *
 971PointerType_from_param(PyObject *type, PyObject *value)
 972{
 973	StgDictObject *typedict;
 974
 975	if (value == Py_None) {
 976		/* ConvParam will convert to a NULL pointer later */
 977		Py_INCREF(value);
 978		return value;
 979	}
 980
 981	typedict = PyType_stgdict(type);
 982	assert(typedict); /* Cannot be NULL for pointer types */
 983
 984	/* If we expect POINTER(<type>), but receive a <type> instance, accept
 985	   it by calling byref(<type>).
 986	*/
 987	switch (PyObject_IsInstance(value, typedict->proto)) {
 988	case 1:
 989		Py_INCREF(value); /* _byref steals a refcount */
 990		return _byref(value);
 991	case -1:
 992		PyErr_Clear();
 993		break;
 994	default:
 995 		break;
 996	}
 997
 998 	if (PointerObject_Check(value) || ArrayObject_Check(value)) {
 999 		/* Array instances are also pointers when
1000 		   the item types are the same.
1001 		*/
1002 		StgDictObject *v = PyObject_stgdict(value);
1003		assert(v); /* Cannot be NULL for pointer or array objects */
1004 		if (PyObject_IsSubclass(v->proto, typedict->proto)) {
1005  			Py_INCREF(value);
1006  			return value;
1007  		}
1008  	}
1009     	return CDataType_from_param(type, value);
1010}
1011
1012static PyMethodDef PointerType_methods[] = {
1013	{ "from_address", CDataType_from_address, METH_O, from_address_doc },
1014	{ "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
1015	{ "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
1016	{ "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
1017	{ "from_param", (PyCFunction)PointerType_from_param, METH_O, from_param_doc},
1018	{ "set_type", (PyCFunction)PointerType_set_type, METH_O },
1019	{ NULL, NULL },
1020};
1021
1022PyTypeObject PointerType_Type = {
1023	PyVarObject_HEAD_INIT(NULL, 0)
1024	"_ctypes.PointerType",				/* tp_name */
1025	0,					/* tp_basicsize */
1026	0,					/* tp_itemsize */
1027	0,					/* tp_dealloc */
1028	0,					/* tp_print */
1029	0,					/* tp_getattr */
1030	0,					/* tp_setattr */
1031	0,					/* tp_compare */
1032	0,			       		/* tp_repr */
1033	0,					/* tp_as_number */
1034	&CDataType_as_sequence,		/* tp_as_sequence */
1035	0,					/* tp_as_mapping */
1036	0,					/* tp_hash */
1037	0,					/* tp_call */
1038	0,					/* tp_str */
1039	0,					/* tp_getattro */
1040	0,					/* tp_setattro */
1041	0,					/* tp_as_buffer */
1042	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1043	"metatype for the Pointer Objects",	/* tp_doc */
1044	(traverseproc)CDataType_traverse,	/* tp_traverse */
1045	(inquiry)CDataType_clear,		/* tp_clear */
1046	0,					/* tp_richcompare */
1047	0,					/* tp_weaklistoffset */
1048	0,					/* tp_iter */
1049	0,					/* tp_iternext */
1050	PointerType_methods,			/* tp_methods */
1051	0,					/* tp_members */
1052	0,					/* tp_getset */
1053	0,					/* tp_base */
1054	0,					/* tp_dict */
1055	0,					/* tp_descr_get */
1056	0,					/* tp_descr_set */
1057	0,					/* tp_dictoffset */
1058	0,					/* tp_init */
1059	0,					/* tp_alloc */
1060	PointerType_new,			/* tp_new */
1061	0,					/* tp_free */
1062};
1063
1064
1065/******************************************************************/
1066/*
1067  ArrayType_Type
1068*/
1069/*
1070  ArrayType_new ensures that the new Array subclass created has a _length_
1071  attribute, and a _type_ attribute.
1072*/
1073
1074static int
1075CharArray_set_raw(CDataObject *self, PyObject *value)
1076{
1077	char *ptr;
1078	Py_ssize_t size;
1079	if (PyBuffer_Check(value)) {
1080		size = Py_TYPE(value)->tp_as_buffer->bf_getreadbuffer(value, 0, (void *)&ptr);
1081		if (size < 0)
1082			return -1;
1083	} else if (-1 == PyString_AsStringAndSize(value, &ptr, &size)) {
1084		return -1;
1085	}
1086	if (size > self->b_size) {
1087		PyErr_SetString(PyExc_ValueError,
1088				"string too long");
1089		return -1;
1090	}
1091
1092	memcpy(self->b_ptr, ptr, size);
1093
1094	return 0;
1095}
1096
1097static PyObject *
1098CharArray_get_raw(CDataObject *self)
1099{
1100	return PyString_FromStringAndSize(self->b_ptr, self->b_size);
1101}
1102
1103static PyObject *
1104CharArray_get_value(CDataObject *self)
1105{
1106	int i;
1107	char *ptr = self->b_ptr;
1108	for (i = 0; i < self->b_size; ++i)
1109		if (*ptr++ == '\0')
1110			break;
1111	return PyString_FromStringAndSize(self->b_ptr, i);
1112}
1113
1114static int
1115CharArray_set_value(CDataObject *self, PyObject *value)
1116{
1117	char *ptr;
1118	Py_ssize_t size;
1119
1120	if (value == NULL) {
1121		PyErr_SetString(PyExc_TypeError,
1122				"can't delete attribute");
1123		return -1;
1124	}
1125
1126	if (PyUnicode_Check(value)) {
1127		value = PyUnicode_AsEncodedString(value,
1128						  conversion_mode_encoding,
1129						  conversion_mode_errors);
1130		if (!value)
1131			return -1;
1132	} else if (!PyString_Check(value)) {
1133		PyErr_Format(PyExc_TypeError,
1134			     "string expected instead of %s instance",
1135			     Py_TYPE(value)->tp_name);
1136		return -1;
1137	} else
1138		Py_INCREF(value);
1139	size = PyString_GET_SIZE(value);
1140	if (size > self->b_size) {
1141		PyErr_SetString(PyExc_ValueError,
1142				"string too long");
1143		Py_DECREF(value);
1144		return -1;
1145	}
1146
1147	ptr = PyString_AS_STRING(value);
1148	memcpy(self->b_ptr, ptr, size);
1149	if (size < self->b_size)
1150		self->b_ptr[size] = '\0';
1151	Py_DECREF(value);
1152
1153	return 0;
1154}
1155
1156static PyGetSetDef CharArray_getsets[] = {
1157	{ "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw,
1158	  "value", NULL },
1159	{ "value", (getter)CharArray_get_value, (setter)CharArray_set_value,
1160	  "string value"},
1161	{ NULL, NULL }
1162};
1163
1164#ifdef CTYPES_UNICODE
1165static PyObject *
1166WCharArray_get_value(CDataObject *self)
1167{
1168	unsigned int i;
1169	wchar_t *ptr = (wchar_t *)self->b_ptr;
1170	for (i = 0; i < self->b_size/sizeof(wchar_t); ++i)
1171		if (*ptr++ == (wchar_t)0)
1172			break;
1173	return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i);
1174}
1175
1176static int
1177WCharArray_set_value(CDataObject *self, PyObject *value)
1178{
1179	Py_ssize_t result = 0;
1180
1181	if (value == NULL) {
1182		PyErr_SetString(PyExc_TypeError,
1183				"can't delete attribute");
1184		return -1;
1185	}
1186	if (PyString_Check(value)) {
1187		value = PyUnicode_FromEncodedObject(value,
1188						    conversion_mode_encoding,
1189						    conversion_mode_errors);
1190		if (!value)
1191			return -1;
1192	} else if (!PyUnicode_Check(value)) {
1193		PyErr_Format(PyExc_TypeError,
1194				"unicode string expected instead of %s instance",
1195				Py_TYPE(value)->tp_name);
1196		return -1;
1197	} else
1198		Py_INCREF(value);
1199	if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) {
1200		PyErr_SetString(PyExc_ValueError,
1201				"string too long");
1202		result = -1;
1203		goto done;
1204	}
1205	result = PyUnicode_AsWideChar((PyUnicodeObject *)value,
1206				      (wchar_t *)self->b_ptr,
1207				      self->b_size/sizeof(wchar_t));
1208	if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t))
1209		((wchar_t *)self->b_ptr)[result] = (wchar_t)0;
1210  done:
1211	Py_DECREF(value);
1212
1213	return result >= 0 ? 0 : -1;
1214}
1215
1216static PyGetSetDef WCharArray_getsets[] = {
1217	{ "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value,
1218	  "string value"},
1219	{ NULL, NULL }
1220};
1221#endif
1222
1223/*
1224  The next three functions copied from Python's typeobject.c.
1225
1226  They are used to attach methods, members, or getsets to a type *after* it
1227  has been created: Arrays of characters have additional getsets to treat them
1228  as strings.
1229 */
1230/*
1231static int
1232add_methods(PyTypeObject *type, PyMethodDef *meth)
1233{
1234	PyObject *dict = type->tp_dict;
1235	for (; meth->ml_name != NULL; meth++) {
1236		PyObject *descr;
1237		descr = PyDescr_NewMethod(type, meth);
1238		if (descr == NULL)
1239			return -1;
1240		if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0)
1241			return -1;
1242		Py_DECREF(descr);
1243	}
1244	return 0;
1245}
1246
1247static int
1248add_members(PyTypeObject *type, PyMemberDef *memb)
1249{
1250	PyObject *dict = type->tp_dict;
1251	for (; memb->name != NULL; memb++) {
1252		PyObject *descr;
1253		descr = PyDescr_NewMember(type, memb);
1254		if (descr == NULL)
1255			return -1;
1256		if (PyDict_SetItemString(dict, memb->name, descr) < 0)
1257			return -1;
1258		Py_DECREF(descr);
1259	}
1260	return 0;
1261}
1262*/
1263
1264static int
1265add_getset(PyTypeObject *type, PyGetSetDef *gsp)
1266{
1267	PyObject *dict = type->tp_dict;
1268	for (; gsp->name != NULL; gsp++) {
1269		PyObject *descr;
1270		descr = PyDescr_NewGetSet(type, gsp);
1271		if (descr == NULL)
1272			return -1;
1273		if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
1274			return -1;
1275		Py_DECREF(descr);
1276	}
1277	return 0;
1278}
1279
1280static PyCArgObject *
1281ArrayType_paramfunc(CDataObject *self)
1282{
1283	PyCArgObject *p = new_CArgObject();
1284	if (p == NULL)
1285		return NULL;
1286	p->tag = 'P';
1287	p->pffi_type = &ffi_type_pointer;
1288	p->value.p = (char *)self->b_ptr;
1289	Py_INCREF(self);
1290	p->obj = (PyObject *)self;
1291	return p;
1292}
1293
1294static PyObject *
1295ArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1296{
1297	PyTypeObject *result;
1298	StgDictObject *stgdict;
1299	StgDictObject *itemdict;
1300	PyObject *proto;
1301	PyObject *typedict;
1302	long length;
1303
1304	Py_ssize_t itemsize, itemalign;
1305	char buf[32];
1306
1307	typedict = PyTuple_GetItem(args, 2);
1308	if (!typedict)
1309		return NULL;
1310
1311	proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */
1312	if (!proto || !PyInt_Check(proto)) {
1313		PyErr_SetString(PyExc_AttributeError,
1314				"class must define a '_length_' attribute, "
1315				"which must be a positive integer");
1316		return NULL;
1317	}
1318	length = PyInt_AS_LONG(proto);
1319
1320	proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
1321	if (!proto) {
1322		PyErr_SetString(PyExc_AttributeError,
1323				"class must define a '_type_' attribute");
1324		return NULL;
1325	}
1326
1327	stgdict = (StgDictObject *)PyObject_CallObject(
1328		(PyObject *)&StgDict_Type, NULL);
1329	if (!stgdict)
1330		return NULL;
1331
1332	itemdict = PyType_stgdict(proto);
1333	if (!itemdict) {
1334		PyErr_SetString(PyExc_TypeError,
1335				"_type_ must have storage info");
1336		Py_DECREF((PyObject *)stgdict);
1337		return NULL;
1338	}
1339
1340	assert(itemdict->format);
1341	if (itemdict->format[0] == '(') {
1342		sprintf(buf, "(%ld,", length);
1343		stgdict->format = alloc_format_string(buf, itemdict->format+1);
1344	} else {
1345		sprintf(buf, "(%ld)", length);
1346		stgdict->format = alloc_format_string(buf, itemdict->format);
1347	}
1348	if (stgdict->format == NULL) {
1349		Py_DECREF((PyObject *)stgdict);
1350		return NULL;
1351	}
1352	stgdict->ndim = itemdict->ndim + 1;
1353	stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim);
1354	if (stgdict->shape == NULL) {
1355		Py_DECREF((PyObject *)stgdict);
1356		return NULL;
1357	}
1358	stgdict->shape[0] = length;
1359	memmove(&stgdict->shape[1], itemdict->shape,
1360		sizeof(Py_ssize_t) * (stgdict->ndim - 1));
1361
1362	itemsize = itemdict->size;
1363	if (length * itemsize < 0) {
1364		PyErr_SetString(PyExc_OverflowError,
1365				"array too large");
1366		return NULL;
1367	}
1368
1369	itemalign = itemdict->align;
1370
1371	if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
1372		stgdict->flags |= TYPEFLAG_HASPOINTER;
1373
1374	stgdict->size = itemsize * length;
1375	stgdict->align = itemalign;
1376	stgdict->length = length;
1377	Py_INCREF(proto);
1378	stgdict->proto = proto;
1379
1380	stgdict->paramfunc = &ArrayType_paramfunc;
1381
1382	/* Arrays are passed as pointers to function calls. */
1383	stgdict->ffi_type_pointer = ffi_type_pointer;
1384
1385	/* create the new instance (which is a class,
1386	   since we are a metatype!) */
1387	result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
1388	if (result == NULL)
1389		return NULL;
1390
1391	/* replace the class dict by our updated spam dict */
1392	if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
1393		Py_DECREF(result);
1394		Py_DECREF((PyObject *)stgdict);
1395		return NULL;
1396	}
1397	Py_DECREF(result->tp_dict);
1398	result->tp_dict = (PyObject *)stgdict;
1399
1400	/* Special case for character arrays.
1401	   A permanent annoyance: char arrays are also strings!
1402	*/
1403	if (itemdict->getfunc == getentry("c")->getfunc) {
1404		if (-1 == add_getset(result, CharArray_getsets))
1405			return NULL;
1406#ifdef CTYPES_UNICODE
1407	} else if (itemdict->getfunc == getentry("u")->getfunc) {
1408		if (-1 == add_getset(result, WCharArray_getsets))
1409			return NULL;
1410#endif
1411	}
1412
1413	return (PyObject *)result;
1414}
1415
1416PyTypeObject ArrayType_Type = {
1417	PyVarObject_HEAD_INIT(NULL, 0)
1418	"_ctypes.ArrayType",			/* tp_name */
1419	0,					/* tp_basicsize */
1420	0,					/* tp_itemsize */
1421	0,					/* tp_dealloc */
1422	0,					/* tp_print */
1423	0,					/* tp_getattr */
1424	0,					/* tp_setattr */
1425	0,					/* tp_compare */
1426	0,			       		/* tp_repr */
1427	0,					/* tp_as_number */
1428	&CDataType_as_sequence,			/* tp_as_sequence */
1429	0,					/* tp_as_mapping */
1430	0,					/* tp_hash */
1431	0,					/* tp_call */
1432	0,					/* tp_str */
1433	0,					/* tp_getattro */
1434	0,					/* tp_setattro */
1435	0,					/* tp_as_buffer */
1436	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1437	"metatype for the Array Objects",	/* tp_doc */
1438	0,					/* tp_traverse */
1439	0,					/* tp_clear */
1440	0,					/* tp_richcompare */
1441	0,					/* tp_weaklistoffset */
1442	0,					/* tp_iter */
1443	0,					/* tp_iternext */
1444	CDataType_methods,			/* tp_methods */
1445	0,					/* tp_members */
1446	0,					/* tp_getset */
1447	0,					/* tp_base */
1448	0,					/* tp_dict */
1449	0,					/* tp_descr_get */
1450	0,					/* tp_descr_set */
1451	0,					/* tp_dictoffset */
1452	0,					/* tp_init */
1453	0,					/* tp_alloc */
1454	ArrayType_new,				/* tp_new */
1455	0,					/* tp_free */
1456};
1457
1458
1459/******************************************************************/
1460/*
1461  SimpleType_Type
1462*/
1463/*
1464
1465SimpleType_new ensures that the new Simple_Type subclass created has a valid
1466_type_ attribute.
1467
1468*/
1469
1470static char *SIMPLE_TYPE_CHARS = "cbBhHiIlLdfuzZqQPXOv?g";
1471
1472static PyObject *
1473c_wchar_p_from_param(PyObject *type, PyObject *value)
1474{
1475	PyObject *as_parameter;
1476#if (PYTHON_API_VERSION < 1012)
1477# error not supported
1478#endif
1479	if (value == Py_None) {
1480		Py_INCREF(Py_None);
1481		return Py_None;
1482	}
1483	if (PyUnicode_Check(value) || PyString_Check(value)) {
1484		PyCArgObject *parg;
1485		struct fielddesc *fd = getentry("Z");
1486
1487		parg = new_CArgObject();
1488		if (parg == NULL)
1489			return NULL;
1490		parg->pffi_type = &ffi_type_pointer;
1491		parg->tag = 'Z';
1492		parg->obj = fd->setfunc(&parg->value, value, 0);
1493		if (parg->obj == NULL) {
1494			Py_DECREF(parg);
1495			return NULL;
1496		}
1497		return (PyObject *)parg;
1498	}
1499	if (PyObject_IsInstance(value, type)) {
1500		Py_INCREF(value);
1501		return value;
1502	}
1503	if (ArrayObject_Check(value) || PointerObject_Check(value)) {
1504		/* c_wchar array instance or pointer(c_wchar(...)) */
1505		StgDictObject *dt = PyObject_stgdict(value);
1506		StgDictObject *dict;
1507		assert(dt); /* Cannot be NULL for pointer or array objects */
1508		dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
1509		if (dict && (dict->setfunc == getentry("u")->setfunc)) {
1510			Py_INCREF(value);
1511			return value;
1512		}
1513	}
1514	if (PyCArg_CheckExact(value)) {
1515		/* byref(c_char(...)) */
1516		PyCArgObject *a = (PyCArgObject *)value;
1517		StgDictObject *dict = PyObject_stgdict(a->obj);
1518		if (dict && (dict->setfunc == getentry("u")->setfunc)) {
1519			Py_INCREF(value);
1520			return value;
1521		}
1522	}
1523
1524	as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
1525	if (as_parameter) {
1526		value = c_wchar_p_from_param(type, as_parameter);
1527		Py_DECREF(as_parameter);
1528		return value;
1529	}
1530	/* XXX better message */
1531	PyErr_SetString(PyExc_TypeError,
1532			"wrong type");
1533	return NULL;
1534}
1535
1536static PyObject *
1537c_char_p_from_param(PyObject *type, PyObject *value)
1538{
1539	PyObject *as_parameter;
1540#if (PYTHON_API_VERSION < 1012)
1541# error not supported
1542#endif
1543	if (value == Py_None) {
1544		Py_INCREF(Py_None);
1545		return Py_None;
1546	}
1547	if (PyString_Check(value) || PyUnicode_Check(value)) {
1548		PyCArgObject *parg;
1549		struct fielddesc *fd = getentry("z");
1550
1551		parg = new_CArgObject();
1552		if (parg == NULL)
1553			return NULL;
1554		parg->pffi_type = &ffi_type_pointer;
1555		parg->tag = 'z';
1556		parg->obj = fd->setfunc(&parg->value, value, 0);
1557		if (parg->obj == NULL) {
1558			Py_DECREF(parg);
1559			return NULL;
1560		}
1561		return (PyObject *)parg;
1562	}
1563	if (PyObject_IsInstance(value, type)) {
1564		Py_INCREF(value);
1565		return value;
1566	}
1567	if (ArrayObject_Check(value) || PointerObject_Check(value)) {
1568		/* c_char array instance or pointer(c_char(...)) */
1569		StgDictObject *dt = PyObject_stgdict(value);
1570		StgDictObject *dict;
1571		assert(dt); /* Cannot be NULL for pointer or array objects */
1572		dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
1573		if (dict && (dict->setfunc == getentry("c")->setfunc)) {
1574			Py_INCREF(value);
1575			return value;
1576		}
1577	}
1578	if (PyCArg_CheckExact(value)) {
1579		/* byref(c_char(...)) */
1580		PyCArgObject *a = (PyCArgObject *)value;
1581		StgDictObject *dict = PyObject_stgdict(a->obj);
1582		if (dict && (dict->setfunc == getentry("c")->setfunc)) {
1583			Py_INCREF(value);
1584			return value;
1585		}
1586	}
1587
1588	as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
1589	if (as_parameter) {
1590		value = c_char_p_from_param(type, as_parameter);
1591		Py_DECREF(as_parameter);
1592		return value;
1593	}
1594	/* XXX better message */
1595	PyErr_SetString(PyExc_TypeError,
1596			"wrong type");
1597	return NULL;
1598}
1599
1600static PyObject *
1601c_void_p_from_param(PyObject *type, PyObject *value)
1602{
1603	StgDictObject *stgd;
1604	PyObject *as_parameter;
1605#if (PYTHON_API_VERSION < 1012)
1606# error not supported
1607#endif
1608
1609/* None */
1610	if (value == Py_None) {
1611		Py_INCREF(Py_None);
1612		return Py_None;
1613	}
1614	/* Should probably allow buffer interface as well */
1615/* int, long */
1616	if (PyInt_Check(value) || PyLong_Check(value)) {
1617		PyCArgObject *parg;
1618		struct fielddesc *fd = getentry("P");
1619
1620		parg = new_CArgObject();
1621		if (parg == NULL)
1622			return NULL;
1623		parg->pffi_type = &ffi_type_pointer;
1624		parg->tag = 'P';
1625		parg->obj = fd->setfunc(&parg->value, value, 0);
1626		if (parg->obj == NULL) {
1627			Py_DECREF(parg);
1628			return NULL;
1629		}
1630		return (PyObject *)parg;
1631	}
1632/* string */
1633	if (PyString_Check(value)) {
1634		PyCArgObject *parg;
1635		struct fielddesc *fd = getentry("z");
1636
1637		parg = new_CArgObject();
1638		if (parg == NULL)
1639			return NULL;
1640		parg->pffi_type = &ffi_type_pointer;
1641		parg->tag = 'z';
1642		parg->obj = fd->setfunc(&parg->value, value, 0);
1643		if (parg->obj == NULL) {
1644			Py_DECREF(parg);
1645			return NULL;
1646		}
1647		return (PyObject *)parg;
1648	}
1649/* unicode */
1650	if (PyUnicode_Check(value)) {
1651		PyCArgObject *parg;
1652		struct fielddesc *fd = getentry("Z");
1653
1654		parg = new_CArgObject();
1655		if (parg == NULL)
1656			return NULL;
1657		parg->pffi_type = &ffi_type_pointer;
1658		parg->tag = 'Z';
1659		parg->obj = fd->setfunc(&parg->value, value, 0);
1660		if (parg->obj == NULL) {
1661			Py_DECREF(parg);
1662			return NULL;
1663		}
1664		return (PyObject *)parg;
1665	}
1666/* c_void_p instance (or subclass) */
1667	if (PyObject_IsInstance(value, type)) {
1668		/* c_void_p instances */
1669		Py_INCREF(value);
1670		return value;
1671	}
1672/* ctypes array or pointer instance */
1673	if (ArrayObject_Check(value) || PointerObject_Check(value)) {
1674		/* Any array or pointer is accepted */
1675		Py_INCREF(value);
1676		return value;
1677	}
1678/* byref(...) */
1679	if (PyCArg_CheckExact(value)) {
1680		/* byref(c_xxx()) */
1681		PyCArgObject *a = (PyCArgObject *)value;
1682		if (a->tag == 'P') {
1683			Py_INCREF(value);
1684			return value;
1685		}
1686	}
1687/* function pointer */
1688	if (CFuncPtrObject_Check(value)) {
1689		PyCArgObject *parg;
1690		CFuncPtrObject *func;
1691		func = (CFuncPtrObject *)value;
1692		parg = new_CArgObject();
1693		if (parg == NULL)
1694			return NULL;
1695		parg->pffi_type = &ffi_type_pointer;
1696		parg->tag = 'P';
1697		Py_INCREF(value);
1698		parg->value.p = *(void **)func->b_ptr;
1699		parg->obj = value;
1700		return (PyObject *)parg;
1701	}
1702/* c_char_p, c_wchar_p */
1703	stgd = PyObject_stgdict(value);
1704	if (stgd && CDataObject_Check(value) && stgd->proto && PyString_Check(stgd->proto)) {
1705		PyCArgObject *parg;
1706
1707		switch (PyString_AS_STRING(stgd->proto)[0]) {
1708		case 'z': /* c_char_p */
1709		case 'Z': /* c_wchar_p */
1710			parg = new_CArgObject();
1711			if (parg == NULL)
1712				return NULL;
1713			parg->pffi_type = &ffi_type_pointer;
1714			parg->tag = 'Z';
1715			Py_INCREF(value);
1716			parg->obj = value;
1717			/* Remember: b_ptr points to where the pointer is stored! */
1718			parg->value.p = *(void **)(((CDataObject *)value)->b_ptr);
1719			return (PyObject *)parg;
1720		}
1721	}
1722
1723	as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
1724	if (as_parameter) {
1725		value = c_void_p_from_param(type, as_parameter);
1726		Py_DECREF(as_parameter);
1727		return value;
1728	}
1729	/* XXX better message */
1730	PyErr_SetString(PyExc_TypeError,
1731			"wrong type");
1732	return NULL;
1733}
1734#if (PYTHON_API_VERSION >= 1012)
1735
1736static PyMethodDef c_void_p_method = { "from_param", c_void_p_from_param, METH_O };
1737static PyMethodDef c_char_p_method = { "from_param", c_char_p_from_param, METH_O };
1738static PyMethodDef c_wchar_p_method = { "from_param", c_wchar_p_from_param, METH_O };
1739
1740#else
1741#error
1742static PyMethodDef c_void_p_method = { "from_param", c_void_p_from_param, METH_VARARGS };
1743static PyMethodDef c_char_p_method = { "from_param", c_char_p_from_param, METH_VARARGS };
1744static PyMethodDef c_wchar_p_method = { "from_param", c_wchar_p_from_param, METH_VARARGS };
1745
1746#endif
1747
1748static PyObject *CreateSwappedType(PyTypeObject *type, PyObject *args, PyObject *kwds,
1749				   PyObject *proto, struct fielddesc *fmt)
1750{
1751	PyTypeObject *result;
1752	StgDictObject *stgdict;
1753	PyObject *name = PyTuple_GET_ITEM(args, 0);
1754	PyObject *swapped_args;
1755	static PyObject *suffix;
1756	Py_ssize_t i;
1757
1758	swapped_args = PyTuple_New(PyTuple_GET_SIZE(args));
1759	if (!swapped_args)
1760		return NULL;
1761
1762	if (suffix == NULL)
1763#ifdef WORDS_BIGENDIAN
1764		suffix = PyString_InternFromString("_le");
1765#else
1766		suffix = PyString_InternFromString("_be");
1767#endif
1768
1769	Py_INCREF(name);
1770	PyString_Concat(&name, suffix);
1771	if (name == NULL)
1772		return NULL;
1773
1774	PyTuple_SET_ITEM(swapped_args, 0, name);
1775	for (i=1; i<PyTuple_GET_SIZE(args); ++i) {
1776		PyObject *v = PyTuple_GET_ITEM(args, i);
1777		Py_INCREF(v);
1778		PyTuple_SET_ITEM(swapped_args, i, v);
1779	}
1780
1781	/* create the new instance (which is a class,
1782	   since we are a metatype!) */
1783	result = (PyTypeObject *)PyType_Type.tp_new(type, swapped_args, kwds);
1784	Py_DECREF(swapped_args);
1785	if (result == NULL)
1786		return NULL;
1787
1788	stgdict = (StgDictObject *)PyObject_CallObject(
1789		(PyObject *)&StgDict_Type, NULL);
1790	if (!stgdict) /* XXX leaks result! */
1791		return NULL;
1792
1793	stgdict->ffi_type_pointer = *fmt->pffi_type;
1794	stgdict->align = fmt->pffi_type->alignment;
1795	stgdict->length = 0;
1796	stgdict->size = fmt->pffi_type->size;
1797	stgdict->setfunc = fmt->setfunc_swapped;
1798	stgdict->getfunc = fmt->getfunc_swapped;
1799
1800	Py_INCREF(proto);
1801	stgdict->proto = proto;
1802
1803	/* replace the class dict by our updated spam dict */
1804	if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
1805		Py_DECREF(result);
1806		Py_DECREF((PyObject *)stgdict);
1807		return NULL;
1808	}
1809	Py_DECREF(result->tp_dict);
1810	result->tp_dict = (PyObject *)stgdict;
1811
1812	return (PyObject *)result;
1813}
1814
1815static PyCArgObject *
1816SimpleType_paramfunc(CDataObject *self)
1817{
1818	StgDictObject *dict;
1819	char *fmt;
1820	PyCArgObject *parg;
1821	struct fielddesc *fd;
1822	
1823	dict = PyObject_stgdict((PyObject *)self);
1824	assert(dict); /* Cannot be NULL for CDataObject instances */
1825	fmt = PyString_AsString(dict->proto);
1826	assert(fmt);
1827
1828	fd = getentry(fmt);
1829	assert(fd);
1830	
1831	parg = new_CArgObject();
1832	if (parg == NULL)
1833		return NULL;
1834	
1835	parg->tag = fmt[0];
1836	parg->pffi_type = fd->pffi_type;
1837	Py_INCREF(self);
1838	parg->obj = (PyObject *)self;
1839	memcpy(&parg->value, self->b_ptr, self->b_size);
1840	return parg;	
1841}
1842
1843static PyObject *
1844SimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1845{
1846	PyTypeObject *result;
1847	StgDictObject *stgdict;
1848	PyObject *proto;
1849	const char *proto_str;
1850	Py_ssize_t proto_len;
1851	PyMethodDef *ml;
1852	struct fielddesc *fmt;
1853
1854	/* create the new instance (which is a class,
1855	   since we are a metatype!) */
1856	result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
1857	if (result == NULL)
1858		return NULL;
1859
1860	proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */
1861	if (!proto) {
1862		PyErr_SetString(PyExc_AttributeError,
1863				"class must define a '_type_' attribute");
1864  error:
1865		Py_XDECREF(proto);
1866		Py_XDECREF(result);
1867		return NULL;
1868	}
1869	if (PyString_Check(proto)) {
1870		proto_str = PyString_AS_STRING(proto);
1871		proto_len = PyString_GET_SIZE(proto);
1872	} else {
1873		PyErr_SetString(PyExc_TypeError,
1874			"class must define a '_type_' string attribute");
1875		goto error;
1876	}
1877	if (proto_len != 1) {
1878		PyErr_SetString(PyExc_ValueError,
1879				"class must define a '_type_' attribute "
1880				"which must be a string of length 1");
1881		goto error;
1882	}
1883	if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) {
1884		PyErr_Format(PyExc_AttributeError,
1885			     "class must define a '_type_' attribute which must be\n"
1886			     "a single character string containing one of '%s'.",
1887			     SIMPLE_TYPE_CHARS);
1888		goto error;
1889	}
1890	fmt = getentry(PyString_AS_STRING(proto));
1891	if (fmt == NULL) {
1892		Py_DECREF(result);
1893		PyErr_Format(PyExc_ValueError,
1894			     "_type_ '%s' not supported",
1895			     PyString_AS_STRING(proto));
1896		return NULL;
1897	}
1898
1899	stgdict = (StgDictObject *)PyObject_CallObject(
1900		(PyObject *)&StgDict_Type, NULL);
1901	if (!stgdict)
1902		return NULL;
1903
1904	stgdict->ffi_type_pointer = *fmt->pffi_type;
1905	stgdict->align = fmt->pffi_type->alignment;
1906	stgdict->length = 0;
1907	stgdict->size = fmt->pffi_type->size;
1908	stgdict->setfunc = fmt->setfunc;
1909	stgdict->getfunc = fmt->getfunc;
1910#ifdef WORDS_BIGENDIAN
1911	stgdict->format = alloc_format_string(">", proto_str);
1912#else
1913	stgdict->format = alloc_format_string("<", proto_str);
1914#endif
1915	if (stgdict->format == NULL) {
1916		Py_DECREF(result);
1917		Py_DECREF((PyObject *)stgdict);
1918		return NULL;
1919	}
1920
1921	stgdict->paramfunc = SimpleType_paramfunc;
1922/*
1923	if (result->tp_base != &Simple_Type) {
1924		stgdict->setfunc = NULL;
1925		stgdict->getfunc = NULL;
1926	}
1927*/
1928
1929	/* This consumes the refcount on proto which we have */
1930	stgdict->proto = proto;
1931
1932	/* replace the class dict by our updated spam dict */
1933	if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
1934		Py_DECREF(result);
1935		Py_DECREF((PyObject *)stgdict);
1936		return NULL;
1937	}
1938	Py_DECREF(result->tp_dict);
1939	result->tp_dict = (PyObject *)stgdict;
1940
1941	/* Install from_param class methods in ctypes base classes.
1942	   Overrides the SimpleType_from_param generic method.
1943	 */
1944	if (result->tp_base == &Simple_Type) {
1945		switch (PyString_AS_STRING(proto)[0]) {
1946		case 'z': /* c_char_p */
1947			ml = &c_char_p_method;
1948			stgdict->flags |= TYPEFLAG_ISPOINTER;
1949			break;
1950		case 'Z': /* c_wchar_p */
1951			ml = &c_wchar_p_method;
1952			stgdict->flags |= TYPEFLAG_ISPOINTER;
1953			break;
1954		case 'P': /* c_void_p */
1955			ml = &c_void_p_method;
1956			stgdict->flags |= TYPEFLAG_ISPOINTER;
1957			break;
1958		case 's':
1959		case 'X':
1960		case 'O':
1961			ml = NULL;
1962			stgdict->flags |= TYPEFLAG_ISPOINTER;
1963			break;
1964		default:
1965			ml = NULL;
1966			break;
1967		}
1968			
1969		if (ml) {
1970#if (PYTHON_API_VERSION >= 1012)
1971			PyObject *meth;
1972			int x;
1973			meth = PyDescr_NewClassMethod(result, ml);
1974			if (!me

Large files files are truncated, but you can click here to view the full file