cfield.c revision 5c6af808f7721787dcce1bc6bfe14f225f9db6f3
1/*****************************************************************
2  This file should be kept compatible with Python 2.3, see PEP 291.
3 *****************************************************************/
4
5#include "Python.h"
6
7#include <ffi.h>
8#ifdef MS_WIN32
9#include <windows.h>
10#endif
11#include "ctypes.h"
12
13/******************************************************************/
14/*
15  PyCField_Type
16*/
17static PyObject *
18PyCField_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
19{
20	CFieldObject *obj;
21	obj = (CFieldObject *)type->tp_alloc(type, 0);
22	return (PyObject *)obj;
23}
24
25/*
26 * Expects the size, index and offset for the current field in *psize and
27 * *poffset, stores the total size so far in *psize, the offset for the next
28 * field in *poffset, the alignment requirements for the current field in
29 * *palign, and returns a field desriptor for this field.
30 */
31/*
32 * bitfields extension:
33 * bitsize != 0: this is a bit field.
34 * pbitofs points to the current bit offset, this will be updated.
35 * prev_desc points to the type of the previous bitfield, if any.
36 */
37PyObject *
38PyCField_FromDesc(PyObject *desc, Py_ssize_t index,
39		Py_ssize_t *pfield_size, int bitsize, int *pbitofs,
40		Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign,
41		int pack, int big_endian)
42{
43	CFieldObject *self;
44	PyObject *proto;
45	Py_ssize_t size, align, length;
46	SETFUNC setfunc = NULL;
47	GETFUNC getfunc = NULL;
48	StgDictObject *dict;
49	int fieldtype;
50#define NO_BITFIELD 0
51#define NEW_BITFIELD 1
52#define CONT_BITFIELD 2
53#define EXPAND_BITFIELD 3
54
55	self = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type,
56						   NULL);
57	if (self == NULL)
58		return NULL;
59	dict = PyType_stgdict(desc);
60	if (!dict) {
61		PyErr_SetString(PyExc_TypeError,
62				"has no _stginfo_");
63		Py_DECREF(self);
64		return NULL;
65	}
66	if (bitsize /* this is a bitfield request */
67	    && *pfield_size /* we have a bitfield open */
68#ifdef MS_WIN32
69	    /* MSVC, GCC with -mms-bitfields */
70	    && dict->size * 8 == *pfield_size
71#else
72	    /* GCC */
73	    && dict->size * 8 <= *pfield_size
74#endif
75	    && (*pbitofs + bitsize) <= *pfield_size) {
76		/* continue bit field */
77		fieldtype = CONT_BITFIELD;
78#ifndef MS_WIN32
79	} else if (bitsize /* this is a bitfield request */
80	    && *pfield_size /* we have a bitfield open */
81	    && dict->size * 8 >= *pfield_size
82	    && (*pbitofs + bitsize) <= dict->size * 8) {
83		/* expand bit field */
84		fieldtype = EXPAND_BITFIELD;
85#endif
86	} else if (bitsize) {
87		/* start new bitfield */
88		fieldtype = NEW_BITFIELD;
89		*pbitofs = 0;
90		*pfield_size = dict->size * 8;
91	} else {
92		/* not a bit field */
93		fieldtype = NO_BITFIELD;
94		*pbitofs = 0;
95		*pfield_size = 0;
96	}
97
98	size = dict->size;
99	length = dict->length;
100	proto = desc;
101
102	/*  Field descriptors for 'c_char * n' are be scpecial cased to
103	    return a Python string instead of an Array object instance...
104	*/
105	if (PyCArrayTypeObject_Check(proto)) {
106		StgDictObject *adict = PyType_stgdict(proto);
107		StgDictObject *idict;
108		if (adict && adict->proto) {
109			idict = PyType_stgdict(adict->proto);
110			if (!idict) {
111				PyErr_SetString(PyExc_TypeError,
112						"has no _stginfo_");
113				Py_DECREF(self);
114				return NULL;
115			}
116			if (idict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
117				struct fielddesc *fd = _ctypes_get_fielddesc("s");
118				getfunc = fd->getfunc;
119				setfunc = fd->setfunc;
120			}
121#ifdef CTYPES_UNICODE
122			if (idict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
123				struct fielddesc *fd = _ctypes_get_fielddesc("U");
124				getfunc = fd->getfunc;
125				setfunc = fd->setfunc;
126			}
127#endif
128		}
129	}
130
131	self->setfunc = setfunc;
132	self->getfunc = getfunc;
133	self->index = index;
134
135	Py_INCREF(proto);
136	self->proto = proto;
137
138	switch (fieldtype) {
139	case NEW_BITFIELD:
140		if (big_endian)
141			self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
142		else
143			self->size = (bitsize << 16) + *pbitofs;
144		*pbitofs = bitsize;
145		/* fall through */
146	case NO_BITFIELD:
147		if (pack)
148			align = min(pack, dict->align);
149		else
150			align = dict->align;
151		if (align && *poffset % align) {
152			Py_ssize_t delta = align - (*poffset % align);
153			*psize += delta;
154			*poffset += delta;
155		}
156
157		if (bitsize == 0)
158			self->size = size;
159		*psize += size;
160
161		self->offset = *poffset;
162		*poffset += size;
163
164		*palign = align;
165		break;
166
167	case EXPAND_BITFIELD:
168		*poffset += dict->size - *pfield_size/8;
169		*psize += dict->size - *pfield_size/8;
170
171		*pfield_size = dict->size * 8;
172
173		if (big_endian)
174			self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
175		else
176			self->size = (bitsize << 16) + *pbitofs;
177
178		self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
179		*pbitofs += bitsize;
180		break;
181
182	case CONT_BITFIELD:
183		if (big_endian)
184			self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
185		else
186			self->size = (bitsize << 16) + *pbitofs;
187
188		self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
189		*pbitofs += bitsize;
190		break;
191	}
192
193	return (PyObject *)self;
194}
195
196static int
197PyCField_set(CFieldObject *self, PyObject *inst, PyObject *value)
198{
199	CDataObject *dst;
200	char *ptr;
201	assert(CDataObject_Check(inst));
202	dst = (CDataObject *)inst;
203	ptr = dst->b_ptr + self->offset;
204	if (value == NULL) {
205		PyErr_SetString(PyExc_TypeError,
206				"can't delete attribute");
207		return -1;
208	}
209	return PyCData_set(inst, self->proto, self->setfunc, value,
210			 self->index, self->size, ptr);
211}
212
213static PyObject *
214PyCField_get(CFieldObject *self, PyObject *inst, PyTypeObject *type)
215{
216	CDataObject *src;
217	if (inst == NULL) {
218		Py_INCREF(self);
219		return (PyObject *)self;
220	}
221	assert(CDataObject_Check(inst));
222	src = (CDataObject *)inst;
223	return PyCData_get(self->proto, self->getfunc, inst,
224			 self->index, self->size, src->b_ptr + self->offset);
225}
226
227static PyObject *
228PyCField_get_offset(PyObject *self, void *data)
229{
230	return PyInt_FromSsize_t(((CFieldObject *)self)->offset);
231}
232
233static PyObject *
234PyCField_get_size(PyObject *self, void *data)
235{
236	return PyInt_FromSsize_t(((CFieldObject *)self)->size);
237}
238
239static PyGetSetDef PyCField_getset[] = {
240	{ "offset", PyCField_get_offset, NULL, "offset in bytes of this field" },
241	{ "size", PyCField_get_size, NULL, "size in bytes of this field" },
242	{ NULL, NULL, NULL, NULL },
243};
244
245static int
246PyCField_traverse(CFieldObject *self, visitproc visit, void *arg)
247{
248	Py_VISIT(self->proto);
249	return 0;
250}
251
252static int
253PyCField_clear(CFieldObject *self)
254{
255	Py_CLEAR(self->proto);
256	return 0;
257}
258
259static void
260PyCField_dealloc(PyObject *self)
261{
262	PyCField_clear((CFieldObject *)self);
263	self->ob_type->tp_free((PyObject *)self);
264}
265
266static PyObject *
267PyCField_repr(CFieldObject *self)
268{
269	PyObject *result;
270	Py_ssize_t bits = self->size >> 16;
271	Py_ssize_t size = self->size & 0xFFFF;
272	const char *name;
273
274	name = ((PyTypeObject *)self->proto)->tp_name;
275
276	if (bits)
277		result = PyString_FromFormat(
278#if (PY_VERSION_HEX < 0x02050000)
279			"<Field type=%s, ofs=%d:%d, bits=%d>",
280#else
281			"<Field type=%s, ofs=%zd:%zd, bits=%zd>",
282#endif
283			name, self->offset, size, bits);
284	else
285		result = PyString_FromFormat(
286#if (PY_VERSION_HEX < 0x02050000)
287			"<Field type=%s, ofs=%d, size=%d>",
288#else
289			"<Field type=%s, ofs=%zd, size=%zd>",
290#endif
291			name, self->offset, size);
292	return result;
293}
294
295PyTypeObject PyCField_Type = {
296	PyVarObject_HEAD_INIT(NULL, 0)
297	"_ctypes.CField",				/* tp_name */
298	sizeof(CFieldObject),			/* tp_basicsize */
299	0,					/* tp_itemsize */
300	PyCField_dealloc,				/* tp_dealloc */
301	0,					/* tp_print */
302	0,					/* tp_getattr */
303	0,					/* tp_setattr */
304	0,					/* tp_compare */
305	(reprfunc)PyCField_repr,			/* tp_repr */
306	0,					/* tp_as_number */
307	0,					/* tp_as_sequence */
308	0,					/* tp_as_mapping */
309	0,					/* tp_hash */
310	0,					/* tp_call */
311	0,					/* tp_str */
312	0,					/* tp_getattro */
313	0,					/* tp_setattro */
314	0,					/* tp_as_buffer */
315	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
316	"Structure/Union member",		/* tp_doc */
317	(traverseproc)PyCField_traverse,		/* tp_traverse */
318	(inquiry)PyCField_clear,			/* tp_clear */
319	0,					/* tp_richcompare */
320	0,					/* tp_weaklistoffset */
321	0,					/* tp_iter */
322	0,					/* tp_iternext */
323	0,					/* tp_methods */
324	0,					/* tp_members */
325	PyCField_getset,				/* tp_getset */
326	0,					/* tp_base */
327	0,					/* tp_dict */
328	(descrgetfunc)PyCField_get,		/* tp_descr_get */
329	(descrsetfunc)PyCField_set,		/* tp_descr_set */
330	0,					/* tp_dictoffset */
331	0,					/* tp_init */
332	0,					/* tp_alloc */
333	PyCField_new,				/* tp_new */
334	0,					/* tp_free */
335};
336
337
338/******************************************************************/
339/*
340  Accessor functions
341*/
342
343/* Derived from Modules/structmodule.c:
344   Helper routine to get a Python integer and raise the appropriate error
345   if it isn't one */
346
347static int
348get_long(PyObject *v, long *p)
349{
350	long x;
351	if (PyFloat_Check(v)) {
352		PyErr_SetString(PyExc_TypeError,
353				"int expected instead of float");
354		return -1;
355	}
356	x = PyInt_AsUnsignedLongMask(v);
357	if (x == -1 && PyErr_Occurred())
358		return -1;
359	*p = x;
360	return 0;
361}
362
363/* Same, but handling unsigned long */
364
365static int
366get_ulong(PyObject *v, unsigned long *p)
367{
368	unsigned long x;
369	if (PyFloat_Check(v)) {
370		PyErr_SetString(PyExc_TypeError,
371				"int expected instead of float");
372		return -1;
373	}
374	x = PyInt_AsUnsignedLongMask(v);
375	if (x == -1 && PyErr_Occurred())
376		return -1;
377	*p = x;
378	return 0;
379}
380
381#ifdef HAVE_LONG_LONG
382
383/* Same, but handling native long long. */
384
385static int
386get_longlong(PyObject *v, PY_LONG_LONG *p)
387{
388	PY_LONG_LONG x;
389	if (PyFloat_Check(v)) {
390		PyErr_SetString(PyExc_TypeError,
391				"int expected instead of float");
392 		return -1;
393	}
394	x = PyInt_AsUnsignedLongLongMask(v);
395	if (x == -1 && PyErr_Occurred())
396		return -1;
397	*p = x;
398	return 0;
399}
400
401/* Same, but handling native unsigned long long. */
402
403static int
404get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
405{
406	unsigned PY_LONG_LONG x;
407	if (PyFloat_Check(v)) {
408		PyErr_SetString(PyExc_TypeError,
409				"int expected instead of float");
410 		return -1;
411 	}
412	x = PyInt_AsUnsignedLongLongMask(v);
413	if (x == -1 && PyErr_Occurred())
414		return -1;
415	*p = x;
416	return 0;
417}
418
419#endif
420
421/*****************************************************************
422 * Integer fields, with bitfield support
423 */
424
425/* how to decode the size field, for integer get/set functions */
426#define LOW_BIT(x)  ((x) & 0xFFFF)
427#define NUM_BITS(x) ((x) >> 16)
428
429/* This seems nore a compiler issue than a Windows/non-Windows one */
430#ifdef MS_WIN32
431#  define BIT_MASK(size) ((1 << NUM_BITS(size))-1)
432#else
433#  define BIT_MASK(size) ((1LL << NUM_BITS(size))-1)
434#endif
435
436/* This macro CHANGES the first parameter IN PLACE. For proper sign handling,
437   we must first shift left, then right.
438*/
439#define GET_BITFIELD(v, size)						\
440	if (NUM_BITS(size)) {						\
441		v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size));	\
442		v >>= (sizeof(v)*8 - NUM_BITS(size));			\
443	}
444
445/* This macro RETURNS the first parameter with the bit field CHANGED. */
446#define SET(x, v, size)							\
447	(NUM_BITS(size) ?						\
448	 ( ( x & ~(BIT_MASK(size) << LOW_BIT(size)) ) | ( (v & BIT_MASK(size)) << LOW_BIT(size) ) ) \
449	 : v)
450
451/* byte swapping macros */
452#define SWAP_2(v)				\
453	( ( (v >> 8) & 0x00FF) |		\
454	  ( (v << 8) & 0xFF00) )
455
456#define SWAP_4(v)			\
457	( ( (v & 0x000000FF) << 24 ) |  \
458	  ( (v & 0x0000FF00) <<  8 ) |  \
459	  ( (v & 0x00FF0000) >>  8 ) |  \
460	  ( ((v >> 24) & 0xFF)) )
461
462#ifdef _MSC_VER
463#define SWAP_8(v)				\
464	( ( (v & 0x00000000000000FFL) << 56 ) |  \
465	  ( (v & 0x000000000000FF00L) << 40 ) |  \
466	  ( (v & 0x0000000000FF0000L) << 24 ) |  \
467	  ( (v & 0x00000000FF000000L) <<  8 ) |  \
468	  ( (v & 0x000000FF00000000L) >>  8 ) |  \
469	  ( (v & 0x0000FF0000000000L) >> 24 ) |  \
470	  ( (v & 0x00FF000000000000L) >> 40 ) |  \
471	  ( ((v >> 56) & 0xFF)) )
472#else
473#define SWAP_8(v)				\
474	( ( (v & 0x00000000000000FFLL) << 56 ) |  \
475	  ( (v & 0x000000000000FF00LL) << 40 ) |  \
476	  ( (v & 0x0000000000FF0000LL) << 24 ) |  \
477	  ( (v & 0x00000000FF000000LL) <<  8 ) |  \
478	  ( (v & 0x000000FF00000000LL) >>  8 ) |  \
479	  ( (v & 0x0000FF0000000000LL) >> 24 ) |  \
480	  ( (v & 0x00FF000000000000LL) >> 40 ) |  \
481	  ( ((v >> 56) & 0xFF)) )
482#endif
483
484#define SWAP_INT SWAP_4
485
486#if SIZEOF_LONG == 4
487# define SWAP_LONG SWAP_4
488#elif SIZEOF_LONG == 8
489# define SWAP_LONG SWAP_8
490#endif
491/*****************************************************************
492 * The setter methods return an object which must be kept alive, to keep the
493 * data valid which has been stored in the memory block.  The ctypes object
494 * instance inserts this object into its 'b_objects' list.
495 *
496 * For simple Python types like integers or characters, there is nothing that
497 * has to been kept alive, so Py_None is returned in these cases.  But this
498 * makes inspecting the 'b_objects' list, which is accessible from Python for
499 * debugging, less useful.
500 *
501 * So, defining the _CTYPES_DEBUG_KEEP symbol returns the original value
502 * instead of Py_None.
503 */
504
505#ifdef _CTYPES_DEBUG_KEEP
506#define _RET(x) Py_INCREF(x); return x
507#else
508#define _RET(X) Py_INCREF(Py_None); return Py_None
509#endif
510
511/*****************************************************************
512 * integer accessor methods, supporting bit fields
513 */
514
515static PyObject *
516b_set(void *ptr, PyObject *value, Py_ssize_t size)
517{
518	long val;
519	if (get_long(value, &val) < 0)
520		return NULL;
521	*(signed char *)ptr = (signed char)SET(*(signed char *)ptr, (signed char)val, size);
522	_RET(value);
523}
524
525
526static PyObject *
527b_get(void *ptr, Py_ssize_t size)
528{
529	signed char val = *(signed char *)ptr;
530	GET_BITFIELD(val, size);
531	return PyInt_FromLong(val);
532}
533
534static PyObject *
535B_set(void *ptr, PyObject *value, Py_ssize_t size)
536{
537	unsigned long val;
538	if (get_ulong(value, &val) < 0)
539		return NULL;
540	*(unsigned char *)ptr = (unsigned char)SET(*(unsigned char*)ptr,
541						   (unsigned short)val, size);
542	_RET(value);
543}
544
545
546static PyObject *
547B_get(void *ptr, Py_ssize_t size)
548{
549	unsigned char val = *(unsigned char *)ptr;
550	GET_BITFIELD(val, size);
551	return PyInt_FromLong(val);
552}
553
554static PyObject *
555h_set(void *ptr, PyObject *value, Py_ssize_t size)
556{
557	long val;
558	short x;
559	if (get_long(value, &val) < 0)
560		return NULL;
561	memcpy(&x, ptr, sizeof(x));
562	x = SET(x, (short)val, size);
563	memcpy(ptr, &x, sizeof(x));
564	_RET(value);
565}
566
567
568static PyObject *
569h_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
570{
571	long val;
572	short field;
573	if (get_long(value, &val) < 0)
574		return NULL;
575	memcpy(&field, ptr, sizeof(field));
576	field = SWAP_2(field);
577	field = SET(field, (short)val, size);
578	field = SWAP_2(field);
579	memcpy(ptr, &field, sizeof(field));
580	_RET(value);
581}
582
583static PyObject *
584h_get(void *ptr, Py_ssize_t size)
585{
586	short val;
587	memcpy(&val, ptr, sizeof(val));
588	GET_BITFIELD(val, size);
589	return PyInt_FromLong((long)val);
590}
591
592static PyObject *
593h_get_sw(void *ptr, Py_ssize_t size)
594{
595	short val;
596	memcpy(&val, ptr, sizeof(val));
597	val = SWAP_2(val);
598	GET_BITFIELD(val, size);
599	return PyInt_FromLong(val);
600}
601
602static PyObject *
603H_set(void *ptr, PyObject *value, Py_ssize_t size)
604{
605	unsigned long val;
606	unsigned short x;
607	if (get_ulong(value, &val) < 0)
608		return NULL;
609	memcpy(&x, ptr, sizeof(x));
610	x = SET(x, (unsigned short)val, size);
611	memcpy(ptr, &x, sizeof(x));
612	_RET(value);
613}
614
615static PyObject *
616H_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
617{
618	unsigned long val;
619	unsigned short field;
620	if (get_ulong(value, &val) < 0)
621		return NULL;
622	memcpy(&field, ptr, sizeof(field));
623	field = SWAP_2(field);
624	field = SET(field, (unsigned short)val, size);
625	field = SWAP_2(field);
626	memcpy(ptr, &field, sizeof(field));
627	_RET(value);
628}
629
630
631static PyObject *
632H_get(void *ptr, Py_ssize_t size)
633{
634	unsigned short val;
635	memcpy(&val, ptr, sizeof(val));
636	GET_BITFIELD(val, size);
637	return PyInt_FromLong(val);
638}
639
640static PyObject *
641H_get_sw(void *ptr, Py_ssize_t size)
642{
643	unsigned short val;
644	memcpy(&val, ptr, sizeof(val));
645	val = SWAP_2(val);
646	GET_BITFIELD(val, size);
647	return PyInt_FromLong(val);
648}
649
650static PyObject *
651i_set(void *ptr, PyObject *value, Py_ssize_t size)
652{
653	long val;
654	int x;
655	if (get_long(value, &val) < 0)
656		return NULL;
657	memcpy(&x, ptr, sizeof(x));
658	x = SET(x, (int)val, size);
659	memcpy(ptr, &x, sizeof(x));
660	_RET(value);
661}
662
663static PyObject *
664i_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
665{
666	long val;
667	int field;
668	if (get_long(value, &val) < 0)
669		return NULL;
670	memcpy(&field, ptr, sizeof(field));
671	field = SWAP_INT(field);
672	field = SET(field, (int)val, size);
673	field = SWAP_INT(field);
674	memcpy(ptr, &field, sizeof(field));
675	_RET(value);
676}
677
678
679static PyObject *
680i_get(void *ptr, Py_ssize_t size)
681{
682	int val;
683	memcpy(&val, ptr, sizeof(val));
684	GET_BITFIELD(val, size);
685	return PyInt_FromLong(val);
686}
687
688static PyObject *
689i_get_sw(void *ptr, Py_ssize_t size)
690{
691	int val;
692	memcpy(&val, ptr, sizeof(val));
693	val = SWAP_INT(val);
694	GET_BITFIELD(val, size);
695	return PyInt_FromLong(val);
696}
697
698#ifdef MS_WIN32
699/* short BOOL - VARIANT_BOOL */
700static PyObject *
701vBOOL_set(void *ptr, PyObject *value, Py_ssize_t size)
702{
703	switch (PyObject_IsTrue(value)) {
704	case -1:
705		return NULL;
706	case 0:
707		*(short int *)ptr = VARIANT_FALSE;
708		_RET(value);
709	default:
710		*(short int *)ptr = VARIANT_TRUE;
711		_RET(value);
712	}
713}
714
715static PyObject *
716vBOOL_get(void *ptr, Py_ssize_t size)
717{
718	return PyBool_FromLong((long)*(short int *)ptr);
719}
720#endif
721
722#ifdef HAVE_C99_BOOL
723#define BOOL_TYPE _Bool
724#else
725#define BOOL_TYPE char
726#undef SIZEOF__BOOL
727#define SIZEOF__BOOL 1
728#endif
729
730static PyObject *
731bool_set(void *ptr, PyObject *value, Py_ssize_t size)
732{
733	switch (PyObject_IsTrue(value)) {
734	case -1:
735		return NULL;
736	case 0:
737		*(BOOL_TYPE *)ptr = 0;
738		_RET(value);
739	default:
740		*(BOOL_TYPE *)ptr = 1;
741		_RET(value);
742	}
743}
744
745static PyObject *
746bool_get(void *ptr, Py_ssize_t size)
747{
748	return PyBool_FromLong((long)*(BOOL_TYPE *)ptr);
749}
750
751static PyObject *
752I_set(void *ptr, PyObject *value, Py_ssize_t size)
753{
754	unsigned long val;
755	unsigned int x;
756	if (get_ulong(value, &val) < 0)
757		return  NULL;
758	memcpy(&x, ptr, sizeof(x));
759	x = SET(x, (unsigned int)val, size);
760	memcpy(ptr, &x, sizeof(x));
761	_RET(value);
762}
763
764static PyObject *
765I_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
766{
767	unsigned long val;
768	unsigned int field;
769	if (get_ulong(value, &val) < 0)
770		return  NULL;
771	memcpy(&field, ptr, sizeof(field));
772	field = (unsigned int)SET(field, (unsigned int)val, size);
773	field = SWAP_INT(field);
774	memcpy(ptr, &field, sizeof(field));
775	_RET(value);
776}
777
778
779static PyObject *
780I_get(void *ptr, Py_ssize_t size)
781{
782	unsigned int val;
783	memcpy(&val, ptr, sizeof(val));
784	GET_BITFIELD(val, size);
785	return PyLong_FromUnsignedLong(val);
786}
787
788static PyObject *
789I_get_sw(void *ptr, Py_ssize_t size)
790{
791	unsigned int val;
792	memcpy(&val, ptr, sizeof(val));
793	val = SWAP_INT(val);
794	GET_BITFIELD(val, size);
795	return PyLong_FromUnsignedLong(val);
796}
797
798static PyObject *
799l_set(void *ptr, PyObject *value, Py_ssize_t size)
800{
801	long val;
802	long x;
803	if (get_long(value, &val) < 0)
804		return NULL;
805	memcpy(&x, ptr, sizeof(x));
806	x = SET(x, val, size);
807	memcpy(ptr, &x, sizeof(x));
808	_RET(value);
809}
810
811static PyObject *
812l_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
813{
814	long val;
815	long field;
816	if (get_long(value, &val) < 0)
817		return NULL;
818	memcpy(&field, ptr, sizeof(field));
819	field = SWAP_LONG(field);
820	field = (long)SET(field, val, size);
821	field = SWAP_LONG(field);
822	memcpy(ptr, &field, sizeof(field));
823	_RET(value);
824}
825
826
827static PyObject *
828l_get(void *ptr, Py_ssize_t size)
829{
830	long val;
831	memcpy(&val, ptr, sizeof(val));
832	GET_BITFIELD(val, size);
833	return PyInt_FromLong(val);
834}
835
836static PyObject *
837l_get_sw(void *ptr, Py_ssize_t size)
838{
839	long val;
840	memcpy(&val, ptr, sizeof(val));
841	val = SWAP_LONG(val);
842	GET_BITFIELD(val, size);
843	return PyInt_FromLong(val);
844}
845
846static PyObject *
847L_set(void *ptr, PyObject *value, Py_ssize_t size)
848{
849	unsigned long val;
850	unsigned long x;
851	if (get_ulong(value, &val) < 0)
852		return  NULL;
853	memcpy(&x, ptr, sizeof(x));
854	x = SET(x, val, size);
855	memcpy(ptr, &x, sizeof(x));
856	_RET(value);
857}
858
859static PyObject *
860L_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
861{
862	unsigned long val;
863	unsigned long field;
864	if (get_ulong(value, &val) < 0)
865		return  NULL;
866	memcpy(&field, ptr, sizeof(field));
867	field = SWAP_LONG(field);
868	field = (unsigned long)SET(field, val, size);
869	field = SWAP_LONG(field);
870	memcpy(ptr, &field, sizeof(field));
871	_RET(value);
872}
873
874
875static PyObject *
876L_get(void *ptr, Py_ssize_t size)
877{
878	unsigned long val;
879	memcpy(&val, ptr, sizeof(val));
880	GET_BITFIELD(val, size);
881	return PyLong_FromUnsignedLong(val);
882}
883
884static PyObject *
885L_get_sw(void *ptr, Py_ssize_t size)
886{
887	unsigned long val;
888	memcpy(&val, ptr, sizeof(val));
889	val = SWAP_LONG(val);
890	GET_BITFIELD(val, size);
891	return PyLong_FromUnsignedLong(val);
892}
893
894#ifdef HAVE_LONG_LONG
895static PyObject *
896q_set(void *ptr, PyObject *value, Py_ssize_t size)
897{
898	PY_LONG_LONG val;
899	PY_LONG_LONG x;
900	if (get_longlong(value, &val) < 0)
901		return NULL;
902	memcpy(&x, ptr, sizeof(x));
903	x = SET(x, val, size);
904	memcpy(ptr, &x, sizeof(x));
905	_RET(value);
906}
907
908static PyObject *
909q_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
910{
911	PY_LONG_LONG val;
912	PY_LONG_LONG field;
913	if (get_longlong(value, &val) < 0)
914		return NULL;
915	memcpy(&field, ptr, sizeof(field));
916	field = SWAP_8(field);
917	field = (PY_LONG_LONG)SET(field, val, size);
918	field = SWAP_8(field);
919	memcpy(ptr, &field, sizeof(field));
920	_RET(value);
921}
922
923static PyObject *
924q_get(void *ptr, Py_ssize_t size)
925{
926	PY_LONG_LONG val;
927	memcpy(&val, ptr, sizeof(val));
928	GET_BITFIELD(val, size);
929	return PyLong_FromLongLong(val);
930}
931
932static PyObject *
933q_get_sw(void *ptr, Py_ssize_t size)
934{
935	PY_LONG_LONG val;
936	memcpy(&val, ptr, sizeof(val));
937	val = SWAP_8(val);
938	GET_BITFIELD(val, size);
939	return PyLong_FromLongLong(val);
940}
941
942static PyObject *
943Q_set(void *ptr, PyObject *value, Py_ssize_t size)
944{
945	unsigned PY_LONG_LONG val;
946	unsigned PY_LONG_LONG x;
947	if (get_ulonglong(value, &val) < 0)
948		return NULL;
949	memcpy(&x, ptr, sizeof(x));
950	x = SET(x, val, size);
951	memcpy(ptr, &x, sizeof(x));
952	_RET(value);
953}
954
955static PyObject *
956Q_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
957{
958	unsigned PY_LONG_LONG val;
959	unsigned PY_LONG_LONG field;
960	if (get_ulonglong(value, &val) < 0)
961		return NULL;
962	memcpy(&field, ptr, sizeof(field));
963	field = SWAP_8(field);
964	field = (unsigned PY_LONG_LONG)SET(field, val, size);
965	field = SWAP_8(field);
966	memcpy(ptr, &field, sizeof(field));
967	_RET(value);
968}
969
970static PyObject *
971Q_get(void *ptr, Py_ssize_t size)
972{
973	unsigned PY_LONG_LONG val;
974	memcpy(&val, ptr, sizeof(val));
975	GET_BITFIELD(val, size);
976	return PyLong_FromUnsignedLongLong(val);
977}
978
979static PyObject *
980Q_get_sw(void *ptr, Py_ssize_t size)
981{
982	unsigned PY_LONG_LONG val;
983	memcpy(&val, ptr, sizeof(val));
984	val = SWAP_8(val);
985	GET_BITFIELD(val, size);
986	return PyLong_FromUnsignedLongLong(val);
987}
988#endif
989
990/*****************************************************************
991 * non-integer accessor methods, not supporting bit fields
992 */
993
994
995static PyObject *
996g_set(void *ptr, PyObject *value, Py_ssize_t size)
997{
998	long double x;
999
1000	x = PyFloat_AsDouble(value);
1001	if (x == -1 && PyErr_Occurred()) {
1002		PyErr_Format(PyExc_TypeError,
1003			     " float expected instead of %s instance",
1004			     value->ob_type->tp_name);
1005		return NULL;
1006	}
1007	memcpy(ptr, &x, sizeof(long double));
1008	_RET(value);
1009}
1010
1011static PyObject *
1012g_get(void *ptr, Py_ssize_t size)
1013{
1014	long double val;
1015	memcpy(&val, ptr, sizeof(long double));
1016	return PyFloat_FromDouble(val);
1017}
1018
1019static PyObject *
1020d_set(void *ptr, PyObject *value, Py_ssize_t size)
1021{
1022	double x;
1023
1024	x = PyFloat_AsDouble(value);
1025	if (x == -1 && PyErr_Occurred()) {
1026		PyErr_Format(PyExc_TypeError,
1027			     " float expected instead of %s instance",
1028			     value->ob_type->tp_name);
1029		return NULL;
1030	}
1031	memcpy(ptr, &x, sizeof(double));
1032	_RET(value);
1033}
1034
1035static PyObject *
1036d_get(void *ptr, Py_ssize_t size)
1037{
1038	double val;
1039	memcpy(&val, ptr, sizeof(val));
1040	return PyFloat_FromDouble(val);
1041}
1042
1043static PyObject *
1044d_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
1045{
1046	double x;
1047
1048	x = PyFloat_AsDouble(value);
1049	if (x == -1 && PyErr_Occurred()) {
1050		PyErr_Format(PyExc_TypeError,
1051			     " float expected instead of %s instance",
1052			     value->ob_type->tp_name);
1053		return NULL;
1054	}
1055#ifdef WORDS_BIGENDIAN
1056	if (_PyFloat_Pack8(x, (unsigned char *)ptr, 1))
1057		return NULL;
1058#else
1059	if (_PyFloat_Pack8(x, (unsigned char *)ptr, 0))
1060		return NULL;
1061#endif
1062	_RET(value);
1063}
1064
1065static PyObject *
1066d_get_sw(void *ptr, Py_ssize_t size)
1067{
1068#ifdef WORDS_BIGENDIAN
1069	return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 1));
1070#else
1071	return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 0));
1072#endif
1073}
1074
1075static PyObject *
1076f_set(void *ptr, PyObject *value, Py_ssize_t size)
1077{
1078	float x;
1079
1080	x = (float)PyFloat_AsDouble(value);
1081	if (x == -1 && PyErr_Occurred()) {
1082		PyErr_Format(PyExc_TypeError,
1083			     " float expected instead of %s instance",
1084			     value->ob_type->tp_name);
1085		return NULL;
1086	}
1087	memcpy(ptr, &x, sizeof(x));
1088	_RET(value);
1089}
1090
1091static PyObject *
1092f_get(void *ptr, Py_ssize_t size)
1093{
1094	float val;
1095	memcpy(&val, ptr, sizeof(val));
1096	return PyFloat_FromDouble(val);
1097}
1098
1099static PyObject *
1100f_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
1101{
1102	float x;
1103
1104	x = (float)PyFloat_AsDouble(value);
1105	if (x == -1 && PyErr_Occurred()) {
1106		PyErr_Format(PyExc_TypeError,
1107			     " float expected instead of %s instance",
1108			     value->ob_type->tp_name);
1109		return NULL;
1110	}
1111#ifdef WORDS_BIGENDIAN
1112	if (_PyFloat_Pack4(x, (unsigned char *)ptr, 1))
1113		return NULL;
1114#else
1115	if (_PyFloat_Pack4(x, (unsigned char *)ptr, 0))
1116		return NULL;
1117#endif
1118	_RET(value);
1119}
1120
1121static PyObject *
1122f_get_sw(void *ptr, Py_ssize_t size)
1123{
1124#ifdef WORDS_BIGENDIAN
1125	return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 1));
1126#else
1127	return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 0));
1128#endif
1129}
1130
1131/*
1132  py_object refcounts:
1133
1134  1. If we have a py_object instance, O_get must Py_INCREF the returned
1135  object, of course.  If O_get is called from a function result, no py_object
1136  instance is created - so callproc.c::GetResult has to call Py_DECREF.
1137
1138  2. The memory block in py_object owns a refcount.  So, py_object must call
1139  Py_DECREF on destruction.  Maybe only when b_needsfree is non-zero.
1140*/
1141static PyObject *
1142O_get(void *ptr, Py_ssize_t size)
1143{
1144	PyObject *ob = *(PyObject **)ptr;
1145	if (ob == NULL) {
1146		if (!PyErr_Occurred())
1147			/* Set an error if not yet set */
1148			PyErr_SetString(PyExc_ValueError,
1149					"PyObject is NULL");
1150		return NULL;
1151	}
1152	Py_INCREF(ob);
1153	return ob;
1154}
1155
1156static PyObject *
1157O_set(void *ptr, PyObject *value, Py_ssize_t size)
1158{
1159	/* Hm, does the memory block need it's own refcount or not? */
1160	*(PyObject **)ptr = value;
1161	Py_INCREF(value);
1162	return value;
1163}
1164
1165
1166static PyObject *
1167c_set(void *ptr, PyObject *value, Py_ssize_t size)
1168{
1169	if (!PyString_Check(value) || (1 != PyString_Size(value))) {
1170		PyErr_Format(PyExc_TypeError,
1171			     "one character string expected");
1172		return NULL;
1173	}
1174	*(char *)ptr = PyString_AS_STRING(value)[0];
1175	_RET(value);
1176}
1177
1178
1179static PyObject *
1180c_get(void *ptr, Py_ssize_t size)
1181{
1182	return PyString_FromStringAndSize((char *)ptr, 1);
1183}
1184
1185#ifdef CTYPES_UNICODE
1186/* u - a single wchar_t character */
1187static PyObject *
1188u_set(void *ptr, PyObject *value, Py_ssize_t size)
1189{
1190	Py_ssize_t len;
1191
1192	if (PyString_Check(value)) {
1193		value = PyUnicode_FromEncodedObject(value,
1194						    _ctypes_conversion_encoding,
1195						    _ctypes_conversion_errors);
1196		if (!value)
1197			return NULL;
1198	} else if (!PyUnicode_Check(value)) {
1199		PyErr_Format(PyExc_TypeError,
1200				"unicode string expected instead of %s instance",
1201				value->ob_type->tp_name);
1202		return NULL;
1203	} else
1204		Py_INCREF(value);
1205
1206	len = PyUnicode_GET_SIZE(value);
1207	if (len != 1) {
1208		Py_DECREF(value);
1209		PyErr_SetString(PyExc_TypeError,
1210				"one character unicode string expected");
1211		return NULL;
1212	}
1213
1214	*(wchar_t *)ptr = PyUnicode_AS_UNICODE(value)[0];
1215	Py_DECREF(value);
1216
1217	_RET(value);
1218}
1219
1220
1221static PyObject *
1222u_get(void *ptr, Py_ssize_t size)
1223{
1224	return PyUnicode_FromWideChar((wchar_t *)ptr, 1);
1225}
1226
1227/* U - a unicode string */
1228static PyObject *
1229U_get(void *ptr, Py_ssize_t size)
1230{
1231	PyObject *result;
1232	Py_ssize_t len;
1233	Py_UNICODE *p;
1234
1235	size /= sizeof(wchar_t); /* we count character units here, not bytes */
1236
1237	result = PyUnicode_FromWideChar((wchar_t *)ptr, size);
1238	if (!result)
1239		return NULL;
1240	/* We need 'result' to be able to count the characters with wcslen,
1241	   since ptr may not be NUL terminated.  If the length is smaller (if
1242	   it was actually NUL terminated, we construct a new one and throw
1243	   away the result.
1244	*/
1245	/* chop off at the first NUL character, if any. */
1246	p = PyUnicode_AS_UNICODE(result);
1247	for (len = 0; len < size; ++len)
1248		if (!p[len])
1249			break;
1250
1251	if (len < size) {
1252		PyObject *ob = PyUnicode_FromWideChar((wchar_t *)ptr, len);
1253		Py_DECREF(result);
1254		return ob;
1255	}
1256	return result;
1257}
1258
1259static PyObject *
1260U_set(void *ptr, PyObject *value, Py_ssize_t length)
1261{
1262	Py_ssize_t size;
1263
1264	/* It's easier to calculate in characters than in bytes */
1265	length /= sizeof(wchar_t);
1266
1267	if (PyString_Check(value)) {
1268		value = PyUnicode_FromEncodedObject(value,
1269						    _ctypes_conversion_encoding,
1270						    _ctypes_conversion_errors);
1271		if (!value)
1272			return NULL;
1273	} else if (!PyUnicode_Check(value)) {
1274		PyErr_Format(PyExc_TypeError,
1275				"unicode string expected instead of %s instance",
1276				value->ob_type->tp_name);
1277		return NULL;
1278	} else
1279		Py_INCREF(value);
1280	size = PyUnicode_GET_SIZE(value);
1281	if (size > length) {
1282		PyErr_Format(PyExc_ValueError,
1283#if (PY_VERSION_HEX < 0x02050000)
1284			     "string too long (%d, maximum length %d)",
1285#else
1286			     "string too long (%zd, maximum length %zd)",
1287#endif
1288			     size, length);
1289		Py_DECREF(value);
1290		return NULL;
1291	} else if (size < length-1)
1292		/* copy terminating NUL character if there is space */
1293		size += 1;
1294	PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size);
1295	return value;
1296}
1297
1298#endif
1299
1300static PyObject *
1301s_get(void *ptr, Py_ssize_t size)
1302{
1303	PyObject *result;
1304	size_t slen;
1305
1306	result = PyString_FromString((char *)ptr);
1307	if (!result)
1308		return NULL;
1309	/* chop off at the first NUL character, if any.
1310	 * On error, result will be deallocated and set to NULL.
1311	 */
1312	slen = strlen(PyString_AS_STRING(result));
1313	size = min(size, (Py_ssize_t)slen);
1314	if (result->ob_refcnt == 1) {
1315		/* shorten the result */
1316		_PyString_Resize(&result, size);
1317		return result;
1318	} else
1319		/* cannot shorten the result */
1320		return PyString_FromStringAndSize(ptr, size);
1321}
1322
1323static PyObject *
1324s_set(void *ptr, PyObject *value, Py_ssize_t length)
1325{
1326	char *data;
1327	Py_ssize_t size;
1328
1329	data = PyString_AsString(value);
1330	if (!data)
1331		return NULL;
1332	size = strlen(data);
1333	if (size < length) {
1334		/* This will copy the leading NUL character
1335		 * if there is space for it.
1336		 */
1337		++size;
1338	} else if (size > length) {
1339		PyErr_Format(PyExc_ValueError,
1340#if (PY_VERSION_HEX < 0x02050000)
1341			     "string too long (%d, maximum length %d)",
1342#else
1343			     "string too long (%zd, maximum length %zd)",
1344#endif
1345			     size, length);
1346		return NULL;
1347	}
1348	/* Also copy the terminating NUL character if there is space */
1349	memcpy((char *)ptr, data, size);
1350	_RET(value);
1351}
1352
1353static PyObject *
1354z_set(void *ptr, PyObject *value, Py_ssize_t size)
1355{
1356	if (value == Py_None) {
1357		*(char **)ptr = NULL;
1358		Py_INCREF(value);
1359		return value;
1360	}
1361	if (PyString_Check(value)) {
1362		*(char **)ptr = PyString_AS_STRING(value);
1363		Py_INCREF(value);
1364		return value;
1365	} else if (PyUnicode_Check(value)) {
1366		PyObject *str = PyUnicode_AsEncodedString(value,
1367							  _ctypes_conversion_encoding,
1368							  _ctypes_conversion_errors);
1369		if (str == NULL)
1370			return NULL;
1371		*(char **)ptr = PyString_AS_STRING(str);
1372		return str;
1373	} else if (PyInt_Check(value) || PyLong_Check(value)) {
1374#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
1375		*(char **)ptr = (char *)PyInt_AsUnsignedLongLongMask(value);
1376#else
1377		*(char **)ptr = (char *)PyInt_AsUnsignedLongMask(value);
1378#endif
1379		_RET(value);
1380	}
1381	PyErr_Format(PyExc_TypeError,
1382		     "string or integer address expected instead of %s instance",
1383		     value->ob_type->tp_name);
1384	return NULL;
1385}
1386
1387static PyObject *
1388z_get(void *ptr, Py_ssize_t size)
1389{
1390	/* XXX What about invalid pointers ??? */
1391	if (*(void **)ptr) {
1392#if defined(MS_WIN32) && !defined(_WIN32_WCE)
1393		if (IsBadStringPtrA(*(char **)ptr, -1)) {
1394			PyErr_Format(PyExc_ValueError,
1395				     "invalid string pointer %p",
1396				     *(char **)ptr);
1397			return NULL;
1398		}
1399#endif
1400		return PyString_FromString(*(char **)ptr);
1401	} else {
1402		Py_INCREF(Py_None);
1403		return Py_None;
1404	}
1405}
1406
1407#ifdef CTYPES_UNICODE
1408static PyObject *
1409Z_set(void *ptr, PyObject *value, Py_ssize_t size)
1410{
1411	if (value == Py_None) {
1412		*(wchar_t **)ptr = NULL;
1413		Py_INCREF(value);
1414		return value;
1415	}
1416	if (PyString_Check(value)) {
1417		value = PyUnicode_FromEncodedObject(value,
1418						    _ctypes_conversion_encoding,
1419						    _ctypes_conversion_errors);
1420		if (!value)
1421			return NULL;
1422	} else if (PyInt_Check(value) || PyLong_Check(value)) {
1423#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
1424		*(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongLongMask(value);
1425#else
1426		*(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongMask(value);
1427#endif
1428		Py_INCREF(Py_None);
1429		return Py_None;
1430	} else if (!PyUnicode_Check(value)) {
1431		PyErr_Format(PyExc_TypeError,
1432			     "unicode string or integer address expected instead of %s instance",
1433			     value->ob_type->tp_name);
1434		return NULL;
1435	} else
1436		Py_INCREF(value);
1437#ifdef HAVE_USABLE_WCHAR_T
1438	/* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same
1439	   type.  So we can copy directly.  Hm, are unicode objects always NUL
1440	   terminated in Python, internally?
1441	 */
1442	*(wchar_t **)ptr = PyUnicode_AS_UNICODE(value);
1443	return value;
1444#else
1445	{
1446		/* We must create a wchar_t* buffer from the unicode object,
1447		   and keep it alive */
1448		PyObject *keep;
1449		wchar_t *buffer;
1450
1451		int size = PyUnicode_GET_SIZE(value);
1452		size += 1; /* terminating NUL */
1453		size *= sizeof(wchar_t);
1454		buffer = (wchar_t *)PyMem_Malloc(size);
1455		if (!buffer) {
1456			Py_DECREF(value);
1457			return PyErr_NoMemory();
1458		}
1459		memset(buffer, 0, size);
1460		keep = PyCObject_FromVoidPtr(buffer, PyMem_Free);
1461		if (!keep) {
1462			Py_DECREF(value);
1463			PyMem_Free(buffer);
1464			return NULL;
1465		}
1466		*(wchar_t **)ptr = (wchar_t *)buffer;
1467		if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value,
1468					       buffer, PyUnicode_GET_SIZE(value))) {
1469			Py_DECREF(value);
1470			Py_DECREF(keep);
1471			return NULL;
1472		}
1473		Py_DECREF(value);
1474		return keep;
1475	}
1476#endif
1477}
1478
1479static PyObject *
1480Z_get(void *ptr, Py_ssize_t size)
1481{
1482	wchar_t *p;
1483	p = *(wchar_t **)ptr;
1484	if (p) {
1485#if defined(MS_WIN32) && !defined(_WIN32_WCE)
1486		if (IsBadStringPtrW(*(wchar_t **)ptr, -1)) {
1487			PyErr_Format(PyExc_ValueError,
1488				     "invalid string pointer %p",
1489				     *(wchar_t **)ptr);
1490			return NULL;
1491		}
1492#endif
1493		return PyUnicode_FromWideChar(p, wcslen(p));
1494	} else {
1495		Py_INCREF(Py_None);
1496		return Py_None;
1497	}
1498}
1499#endif
1500
1501#ifdef MS_WIN32
1502static PyObject *
1503BSTR_set(void *ptr, PyObject *value, Py_ssize_t size)
1504{
1505	BSTR bstr;
1506
1507	/* convert value into a PyUnicodeObject or NULL */
1508	if (Py_None == value) {
1509		value = NULL;
1510	} else if (PyString_Check(value)) {
1511		value = PyUnicode_FromEncodedObject(value,
1512						    _ctypes_conversion_encoding,
1513						    _ctypes_conversion_errors);
1514		if (!value)
1515			return NULL;
1516	} else if (PyUnicode_Check(value)) {
1517		Py_INCREF(value); /* for the descref below */
1518	} else {
1519		PyErr_Format(PyExc_TypeError,
1520				"unicode string expected instead of %s instance",
1521				value->ob_type->tp_name);
1522		return NULL;
1523	}
1524
1525	/* create a BSTR from value */
1526	if (value) {
1527		Py_ssize_t size = PyUnicode_GET_SIZE(value);
1528		if ((unsigned) size != size) {
1529			PyErr_SetString(PyExc_ValueError, "String too long for BSTR");
1530			return NULL;
1531		}
1532		bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value),
1533					 (unsigned)size);
1534		Py_DECREF(value);
1535	} else
1536		bstr = NULL;
1537
1538	/* free the previous contents, if any */
1539	if (*(BSTR *)ptr)
1540		SysFreeString(*(BSTR *)ptr);
1541
1542	/* and store it */
1543	*(BSTR *)ptr = bstr;
1544
1545	/* We don't need to keep any other object */
1546	_RET(value);
1547}
1548
1549
1550static PyObject *
1551BSTR_get(void *ptr, Py_ssize_t size)
1552{
1553	BSTR p;
1554	p = *(BSTR *)ptr;
1555	if (p)
1556		return PyUnicode_FromWideChar(p, SysStringLen(p));
1557	else {
1558		/* Hm, it seems NULL pointer and zero length string are the
1559		   same in BSTR, see Don Box, p 81
1560		*/
1561		Py_INCREF(Py_None);
1562		return Py_None;
1563	}
1564}
1565#endif
1566
1567static PyObject *
1568P_set(void *ptr, PyObject *value, Py_ssize_t size)
1569{
1570	void *v;
1571	if (value == Py_None) {
1572		*(void **)ptr = NULL;
1573		_RET(value);
1574	}
1575
1576	if (!PyInt_Check(value) && !PyLong_Check(value)) {
1577		PyErr_SetString(PyExc_TypeError,
1578				"cannot be converted to pointer");
1579		return NULL;
1580	}
1581
1582#if SIZEOF_VOID_P <= SIZEOF_LONG
1583	v = (void *)PyInt_AsUnsignedLongMask(value);
1584#else
1585#ifndef HAVE_LONG_LONG
1586#   error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1587#elif SIZEOF_LONG_LONG < SIZEOF_VOID_P
1588#   error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
1589#endif
1590	v = (void *)PyInt_AsUnsignedLongLongMask(value);
1591#endif
1592
1593	if (PyErr_Occurred())
1594		return NULL;
1595
1596	*(void **)ptr = v;
1597	_RET(value);
1598}
1599
1600static PyObject *
1601P_get(void *ptr, Py_ssize_t size)
1602{
1603	if (*(void **)ptr == NULL) {
1604		Py_INCREF(Py_None);
1605		return Py_None;
1606	}
1607	return PyLong_FromVoidPtr(*(void **)ptr);
1608}
1609
1610static struct fielddesc formattable[] = {
1611	{ 's', s_set, s_get, &ffi_type_pointer},
1612	{ 'b', b_set, b_get, &ffi_type_schar},
1613	{ 'B', B_set, B_get, &ffi_type_uchar},
1614	{ 'c', c_set, c_get, &ffi_type_schar},
1615	{ 'd', d_set, d_get, &ffi_type_double, d_set_sw, d_get_sw},
1616	{ 'g', g_set, g_get, &ffi_type_longdouble},
1617	{ 'f', f_set, f_get, &ffi_type_float, f_set_sw, f_get_sw},
1618	{ 'h', h_set, h_get, &ffi_type_sshort, h_set_sw, h_get_sw},
1619	{ 'H', H_set, H_get, &ffi_type_ushort, H_set_sw, H_get_sw},
1620	{ 'i', i_set, i_get, &ffi_type_sint, i_set_sw, i_get_sw},
1621	{ 'I', I_set, I_get, &ffi_type_uint, I_set_sw, I_get_sw},
1622/* XXX Hm, sizeof(int) == sizeof(long) doesn't hold on every platform */
1623/* As soon as we can get rid of the type codes, this is no longer a problem */
1624#if SIZEOF_LONG == 4
1625	{ 'l', l_set, l_get, &ffi_type_sint32, l_set_sw, l_get_sw},
1626	{ 'L', L_set, L_get, &ffi_type_uint32, L_set_sw, L_get_sw},
1627#elif SIZEOF_LONG == 8
1628	{ 'l', l_set, l_get, &ffi_type_sint64, l_set_sw, l_get_sw},
1629	{ 'L', L_set, L_get, &ffi_type_uint64, L_set_sw, L_get_sw},
1630#else
1631# error
1632#endif
1633#ifdef HAVE_LONG_LONG
1634#if SIZEOF_LONG_LONG == 8
1635	{ 'q', q_set, q_get, &ffi_type_sint64, q_set_sw, q_get_sw},
1636	{ 'Q', Q_set, Q_get, &ffi_type_uint64, Q_set_sw, Q_get_sw},
1637#else
1638# error
1639#endif
1640#endif
1641	{ 'P', P_set, P_get, &ffi_type_pointer},
1642	{ 'z', z_set, z_get, &ffi_type_pointer},
1643#ifdef CTYPES_UNICODE
1644	{ 'u', u_set, u_get, NULL}, /* ffi_type set later */
1645	{ 'U', U_set, U_get, &ffi_type_pointer},
1646	{ 'Z', Z_set, Z_get, &ffi_type_pointer},
1647#endif
1648#ifdef MS_WIN32
1649	{ 'X', BSTR_set, BSTR_get, &ffi_type_pointer},
1650	{ 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort},
1651#endif
1652#if SIZEOF__BOOL == 1
1653	{ '?', bool_set, bool_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */
1654#elif SIZEOF__BOOL == SIZEOF_SHORT
1655	{ '?', bool_set, bool_get, &ffi_type_ushort},
1656#elif SIZEOF__BOOL == SIZEOF_INT
1657	{ '?', bool_set, bool_get, &ffi_type_uint, I_set_sw, I_get_sw},
1658#elif SIZEOF__BOOL == SIZEOF_LONG
1659	{ '?', bool_set, bool_get, &ffi_type_ulong, L_set_sw, L_get_sw},
1660#elif SIZEOF__BOOL == SIZEOF_LONG_LONG
1661	{ '?', bool_set, bool_get, &ffi_type_ulong, Q_set_sw, Q_get_sw},
1662#endif /* SIZEOF__BOOL */
1663	{ 'O', O_set, O_get, &ffi_type_pointer},
1664	{ 0, NULL, NULL, NULL},
1665};
1666
1667/*
1668  Ideas: Implement VARIANT in this table, using 'V' code.
1669  Use '?' as code for BOOL.
1670*/
1671
1672struct fielddesc *
1673_ctypes_get_fielddesc(char *fmt)
1674{
1675	static int initialized = 0;
1676	struct fielddesc *table = formattable;
1677
1678	if (!initialized) {
1679		initialized = 1;
1680#ifdef CTYPES_UNICODE
1681		if (sizeof(wchar_t) == sizeof(short))
1682			_ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sshort;
1683		else if (sizeof(wchar_t) == sizeof(int))
1684			_ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sint;
1685		else if (sizeof(wchar_t) == sizeof(long))
1686			_ctypes_get_fielddesc("u")->pffi_type = &ffi_type_slong;
1687#endif
1688	}
1689
1690	for (; table->code; ++table) {
1691		if (table->code == fmt[0])
1692			return table;
1693	}
1694	return NULL;
1695}
1696
1697typedef struct { char c; char x; } s_char;
1698typedef struct { char c; short x; } s_short;
1699typedef struct { char c; int x; } s_int;
1700typedef struct { char c; long x; } s_long;
1701typedef struct { char c; float x; } s_float;
1702typedef struct { char c; double x; } s_double;
1703typedef struct { char c; long double x; } s_long_double;
1704typedef struct { char c; char *x; } s_char_p;
1705typedef struct { char c; void *x; } s_void_p;
1706
1707/*
1708#define CHAR_ALIGN (sizeof(s_char) - sizeof(char))
1709#define SHORT_ALIGN (sizeof(s_short) - sizeof(short))
1710#define INT_ALIGN (sizeof(s_int) - sizeof(int))
1711#define LONG_ALIGN (sizeof(s_long) - sizeof(long))
1712*/
1713#define FLOAT_ALIGN (sizeof(s_float) - sizeof(float))
1714#define DOUBLE_ALIGN (sizeof(s_double) - sizeof(double))
1715#define LONGDOUBLE_ALIGN (sizeof(s_long_double) - sizeof(long double))
1716
1717/* #define CHAR_P_ALIGN (sizeof(s_char_p) - sizeof(char*)) */
1718#define VOID_P_ALIGN (sizeof(s_void_p) - sizeof(void*))
1719
1720/*
1721#ifdef HAVE_USABLE_WCHAR_T
1722typedef struct { char c; wchar_t x; } s_wchar;
1723typedef struct { char c; wchar_t *x; } s_wchar_p;
1724
1725#define WCHAR_ALIGN (sizeof(s_wchar) - sizeof(wchar_t))
1726#define WCHAR_P_ALIGN (sizeof(s_wchar_p) - sizeof(wchar_t*))
1727#endif
1728*/
1729
1730#ifdef HAVE_LONG_LONG
1731typedef struct { char c; PY_LONG_LONG x; } s_long_long;
1732#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
1733#endif
1734
1735/* from ffi.h:
1736typedef struct _ffi_type
1737{
1738	size_t size;
1739	unsigned short alignment;
1740	unsigned short type;
1741	struct _ffi_type **elements;
1742} ffi_type;
1743*/
1744
1745/* align and size are bogus for void, but they must not be zero */
1746ffi_type ffi_type_void = { 1, 1, FFI_TYPE_VOID };
1747
1748ffi_type ffi_type_uint8 = { 1, 1, FFI_TYPE_UINT8 };
1749ffi_type ffi_type_sint8 = { 1, 1, FFI_TYPE_SINT8 };
1750
1751ffi_type ffi_type_uint16 = { 2, 2, FFI_TYPE_UINT16 };
1752ffi_type ffi_type_sint16 = { 2, 2, FFI_TYPE_SINT16 };
1753
1754ffi_type ffi_type_uint32 = { 4, 4, FFI_TYPE_UINT32 };
1755ffi_type ffi_type_sint32 = { 4, 4, FFI_TYPE_SINT32 };
1756
1757ffi_type ffi_type_uint64 = { 8, LONG_LONG_ALIGN, FFI_TYPE_UINT64 };
1758ffi_type ffi_type_sint64 = { 8, LONG_LONG_ALIGN, FFI_TYPE_SINT64 };
1759
1760ffi_type ffi_type_float = { sizeof(float), FLOAT_ALIGN, FFI_TYPE_FLOAT };
1761ffi_type ffi_type_double = { sizeof(double), DOUBLE_ALIGN, FFI_TYPE_DOUBLE };
1762
1763#ifdef ffi_type_longdouble
1764#undef ffi_type_longdouble
1765#endif
1766  /* This is already defined on OSX */
1767ffi_type ffi_type_longdouble = { sizeof(long double), LONGDOUBLE_ALIGN,
1768				 FFI_TYPE_LONGDOUBLE };
1769
1770ffi_type ffi_type_pointer = { sizeof(void *), VOID_P_ALIGN, FFI_TYPE_POINTER };
1771
1772/*---------------- EOF ----------------*/
1773