Manual py3k backport: [svn r74158] Issue #6218: Make io.BytesIO and io.StringIO pickl...
[python.git] / Modules / _ctypes / callproc.c
blobcf17e3aa9df6d2e69d94f0e2db1ec4700c043ffb
1 /*****************************************************************
2 This file should be kept compatible with Python 2.3, see PEP 291.
3 *****************************************************************/
6 /*
7 * History: First version dated from 3/97, derived from my SCMLIB version
8 * for win16.
9 */
11 * Related Work:
12 * - calldll http://www.nightmare.com/software.html
13 * - libffi http://sourceware.cygnus.com/libffi/
14 * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html
15 * and, of course, Don Beaudry's MESS package, but this is more ctypes
16 * related.
21 How are functions called, and how are parameters converted to C ?
23 1. _ctypes.c::PyCFuncPtr_call receives an argument tuple 'inargs' and a
24 keyword dictionary 'kwds'.
26 2. After several checks, _build_callargs() is called which returns another
27 tuple 'callargs'. This may be the same tuple as 'inargs', a slice of
28 'inargs', or a completely fresh tuple, depending on several things (is is a
29 COM method, are 'paramflags' available).
31 3. _build_callargs also calculates bitarrays containing indexes into
32 the callargs tuple, specifying how to build the return value(s) of
33 the function.
35 4. _ctypes_callproc is then called with the 'callargs' tuple. _ctypes_callproc first
36 allocates two arrays. The first is an array of 'struct argument' items, the
37 second array has 'void *' entried.
39 5. If 'converters' are present (converters is a sequence of argtypes'
40 from_param methods), for each item in 'callargs' converter is called and the
41 result passed to ConvParam. If 'converters' are not present, each argument
42 is directly passed to ConvParm.
44 6. For each arg, ConvParam stores the contained C data (or a pointer to it,
45 for structures) into the 'struct argument' array.
47 7. Finally, a loop fills the 'void *' array so that each item points to the
48 data contained in or pointed to by the 'struct argument' array.
50 8. The 'void *' argument array is what _call_function_pointer
51 expects. _call_function_pointer then has very little to do - only some
52 libffi specific stuff, then it calls ffi_call.
54 So, there are 4 data structures holding processed arguments:
55 - the inargs tuple (in PyCFuncPtr_call)
56 - the callargs tuple (in PyCFuncPtr_call)
57 - the 'struct argguments' array
58 - the 'void *' array
62 #include "Python.h"
63 #include "structmember.h"
65 #ifdef MS_WIN32
66 #include <windows.h>
67 #include <tchar.h>
68 #else
69 #include "ctypes_dlfcn.h"
70 #endif
72 #ifdef MS_WIN32
73 #include <malloc.h>
74 #endif
76 #include <ffi.h>
77 #include "ctypes.h"
79 #if defined(_DEBUG) || defined(__MINGW32__)
80 /* Don't use structured exception handling on Windows if this is defined.
81 MingW, AFAIK, doesn't support it.
83 #define DONT_USE_SEH
84 #endif
87 ctypes maintains thread-local storage that has space for two error numbers:
88 private copies of the system 'errno' value and, on Windows, the system error code
89 accessed by the GetLastError() and SetLastError() api functions.
91 Foreign functions created with CDLL(..., use_errno=True), when called, swap
92 the system 'errno' value with the private copy just before the actual
93 function call, and swapped again immediately afterwards. The 'use_errno'
94 parameter defaults to False, in this case 'ctypes_errno' is not touched.
96 On Windows, foreign functions created with CDLL(..., use_last_error=True) or
97 WinDLL(..., use_last_error=True) swap the system LastError value with the
98 ctypes private copy.
100 The values are also swapped immeditately before and after ctypes callback
101 functions are called, if the callbacks are constructed using the new
102 optional use_errno parameter set to True: CFUNCTYPE(..., use_errno=TRUE) or
103 WINFUNCTYPE(..., use_errno=True).
105 New ctypes functions are provided to access the ctypes private copies from
106 Python:
108 - ctypes.set_errno(value) and ctypes.set_last_error(value) store 'value' in
109 the private copy and returns the previous value.
111 - ctypes.get_errno() and ctypes.get_last_error() returns the current ctypes
112 private copies value.
116 This function creates and returns a thread-local Python object that has
117 space to store two integer error numbers; once created the Python object is
118 kept alive in the thread state dictionary as long as the thread itself.
120 PyObject *
121 _ctypes_get_errobj(int **pspace)
123 PyObject *dict = PyThreadState_GetDict();
124 PyObject *errobj;
125 static PyObject *error_object_name;
126 if (dict == 0) {
127 PyErr_SetString(PyExc_RuntimeError,
128 "cannot get thread state");
129 return NULL;
131 if (error_object_name == NULL) {
132 error_object_name = PyString_InternFromString("ctypes.error_object");
133 if (error_object_name == NULL)
134 return NULL;
136 errobj = PyDict_GetItem(dict, error_object_name);
137 if (errobj)
138 Py_INCREF(errobj);
139 else {
140 void *space = PyMem_Malloc(sizeof(int) * 2);
141 if (space == NULL)
142 return NULL;
143 memset(space, 0, sizeof(int) * 2);
144 errobj = PyCObject_FromVoidPtr(space, PyMem_Free);
145 if (errobj == NULL)
146 return NULL;
147 if (-1 == PyDict_SetItem(dict, error_object_name,
148 errobj)) {
149 Py_DECREF(errobj);
150 return NULL;
153 *pspace = (int *)PyCObject_AsVoidPtr(errobj);
154 return errobj;
157 static PyObject *
158 get_error_internal(PyObject *self, PyObject *args, int index)
160 int *space;
161 PyObject *errobj = _ctypes_get_errobj(&space);
162 PyObject *result;
164 if (errobj == NULL)
165 return NULL;
166 result = PyInt_FromLong(space[index]);
167 Py_DECREF(errobj);
168 return result;
171 static PyObject *
172 set_error_internal(PyObject *self, PyObject *args, int index)
174 int new_errno, old_errno;
175 PyObject *errobj;
176 int *space;
178 if (!PyArg_ParseTuple(args, "i", &new_errno))
179 return NULL;
180 errobj = _ctypes_get_errobj(&space);
181 if (errobj == NULL)
182 return NULL;
183 old_errno = space[index];
184 space[index] = new_errno;
185 Py_DECREF(errobj);
186 return PyInt_FromLong(old_errno);
189 static PyObject *
190 get_errno(PyObject *self, PyObject *args)
192 return get_error_internal(self, args, 0);
195 static PyObject *
196 set_errno(PyObject *self, PyObject *args)
198 return set_error_internal(self, args, 0);
201 #ifdef MS_WIN32
203 static PyObject *
204 get_last_error(PyObject *self, PyObject *args)
206 return get_error_internal(self, args, 1);
209 static PyObject *
210 set_last_error(PyObject *self, PyObject *args)
212 return set_error_internal(self, args, 1);
215 PyObject *ComError;
217 static TCHAR *FormatError(DWORD code)
219 TCHAR *lpMsgBuf;
220 DWORD n;
221 n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
222 NULL,
223 code,
224 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
225 (LPTSTR) &lpMsgBuf,
227 NULL);
228 if (n) {
229 while (_istspace(lpMsgBuf[n-1]))
230 --n;
231 lpMsgBuf[n] = _T('\0'); /* rstrip() */
233 return lpMsgBuf;
236 #ifndef DONT_USE_SEH
237 static void SetException(DWORD code, EXCEPTION_RECORD *pr)
239 /* The 'code' is a normal win32 error code so it could be handled by
240 PyErr_SetFromWindowsErr(). However, for some errors, we have additional
241 information not included in the error code. We handle those here and
242 delegate all others to the generic function. */
243 switch (code) {
244 case EXCEPTION_ACCESS_VIOLATION:
245 /* The thread attempted to read from or write
246 to a virtual address for which it does not
247 have the appropriate access. */
248 if (pr->ExceptionInformation[0] == 0)
249 PyErr_Format(PyExc_WindowsError,
250 "exception: access violation reading %p",
251 pr->ExceptionInformation[1]);
252 else
253 PyErr_Format(PyExc_WindowsError,
254 "exception: access violation writing %p",
255 pr->ExceptionInformation[1]);
256 break;
258 case EXCEPTION_BREAKPOINT:
259 /* A breakpoint was encountered. */
260 PyErr_SetString(PyExc_WindowsError,
261 "exception: breakpoint encountered");
262 break;
264 case EXCEPTION_DATATYPE_MISALIGNMENT:
265 /* The thread attempted to read or write data that is
266 misaligned on hardware that does not provide
267 alignment. For example, 16-bit values must be
268 aligned on 2-byte boundaries, 32-bit values on
269 4-byte boundaries, and so on. */
270 PyErr_SetString(PyExc_WindowsError,
271 "exception: datatype misalignment");
272 break;
274 case EXCEPTION_SINGLE_STEP:
275 /* A trace trap or other single-instruction mechanism
276 signaled that one instruction has been executed. */
277 PyErr_SetString(PyExc_WindowsError,
278 "exception: single step");
279 break;
281 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
282 /* The thread attempted to access an array element
283 that is out of bounds, and the underlying hardware
284 supports bounds checking. */
285 PyErr_SetString(PyExc_WindowsError,
286 "exception: array bounds exceeded");
287 break;
289 case EXCEPTION_FLT_DENORMAL_OPERAND:
290 /* One of the operands in a floating-point operation
291 is denormal. A denormal value is one that is too
292 small to represent as a standard floating-point
293 value. */
294 PyErr_SetString(PyExc_WindowsError,
295 "exception: floating-point operand denormal");
296 break;
298 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
299 /* The thread attempted to divide a floating-point
300 value by a floating-point divisor of zero. */
301 PyErr_SetString(PyExc_WindowsError,
302 "exception: float divide by zero");
303 break;
305 case EXCEPTION_FLT_INEXACT_RESULT:
306 /* The result of a floating-point operation cannot be
307 represented exactly as a decimal fraction. */
308 PyErr_SetString(PyExc_WindowsError,
309 "exception: float inexact");
310 break;
312 case EXCEPTION_FLT_INVALID_OPERATION:
313 /* This exception represents any floating-point
314 exception not included in this list. */
315 PyErr_SetString(PyExc_WindowsError,
316 "exception: float invalid operation");
317 break;
319 case EXCEPTION_FLT_OVERFLOW:
320 /* The exponent of a floating-point operation is
321 greater than the magnitude allowed by the
322 corresponding type. */
323 PyErr_SetString(PyExc_WindowsError,
324 "exception: float overflow");
325 break;
327 case EXCEPTION_FLT_STACK_CHECK:
328 /* The stack overflowed or underflowed as the result
329 of a floating-point operation. */
330 PyErr_SetString(PyExc_WindowsError,
331 "exception: stack over/underflow");
332 break;
334 case EXCEPTION_STACK_OVERFLOW:
335 /* The stack overflowed or underflowed as the result
336 of a floating-point operation. */
337 PyErr_SetString(PyExc_WindowsError,
338 "exception: stack overflow");
339 break;
341 case EXCEPTION_FLT_UNDERFLOW:
342 /* The exponent of a floating-point operation is less
343 than the magnitude allowed by the corresponding
344 type. */
345 PyErr_SetString(PyExc_WindowsError,
346 "exception: float underflow");
347 break;
349 case EXCEPTION_INT_DIVIDE_BY_ZERO:
350 /* The thread attempted to divide an integer value by
351 an integer divisor of zero. */
352 PyErr_SetString(PyExc_WindowsError,
353 "exception: integer divide by zero");
354 break;
356 case EXCEPTION_INT_OVERFLOW:
357 /* The result of an integer operation caused a carry
358 out of the most significant bit of the result. */
359 PyErr_SetString(PyExc_WindowsError,
360 "exception: integer overflow");
361 break;
363 case EXCEPTION_PRIV_INSTRUCTION:
364 /* The thread attempted to execute an instruction
365 whose operation is not allowed in the current
366 machine mode. */
367 PyErr_SetString(PyExc_WindowsError,
368 "exception: priviledged instruction");
369 break;
371 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
372 /* The thread attempted to continue execution after a
373 noncontinuable exception occurred. */
374 PyErr_SetString(PyExc_WindowsError,
375 "exception: nocontinuable");
376 break;
378 default:
379 PyErr_SetFromWindowsErr(code);
380 break;
384 static DWORD HandleException(EXCEPTION_POINTERS *ptrs,
385 DWORD *pdw, EXCEPTION_RECORD *record)
387 *pdw = ptrs->ExceptionRecord->ExceptionCode;
388 *record = *ptrs->ExceptionRecord;
389 return EXCEPTION_EXECUTE_HANDLER;
391 #endif
393 static PyObject *
394 check_hresult(PyObject *self, PyObject *args)
396 HRESULT hr;
397 if (!PyArg_ParseTuple(args, "i", &hr))
398 return NULL;
399 if (FAILED(hr))
400 return PyErr_SetFromWindowsErr(hr);
401 return PyInt_FromLong(hr);
404 #endif
406 /**************************************************************/
408 PyCArgObject *
409 PyCArgObject_new(void)
411 PyCArgObject *p;
412 p = PyObject_New(PyCArgObject, &PyCArg_Type);
413 if (p == NULL)
414 return NULL;
415 p->pffi_type = NULL;
416 p->tag = '\0';
417 p->obj = NULL;
418 memset(&p->value, 0, sizeof(p->value));
419 return p;
422 static void
423 PyCArg_dealloc(PyCArgObject *self)
425 Py_XDECREF(self->obj);
426 PyObject_Del(self);
429 static PyObject *
430 PyCArg_repr(PyCArgObject *self)
432 char buffer[256];
433 switch(self->tag) {
434 case 'b':
435 case 'B':
436 sprintf(buffer, "<cparam '%c' (%d)>",
437 self->tag, self->value.b);
438 break;
439 case 'h':
440 case 'H':
441 sprintf(buffer, "<cparam '%c' (%d)>",
442 self->tag, self->value.h);
443 break;
444 case 'i':
445 case 'I':
446 sprintf(buffer, "<cparam '%c' (%d)>",
447 self->tag, self->value.i);
448 break;
449 case 'l':
450 case 'L':
451 sprintf(buffer, "<cparam '%c' (%ld)>",
452 self->tag, self->value.l);
453 break;
455 #ifdef HAVE_LONG_LONG
456 case 'q':
457 case 'Q':
458 sprintf(buffer,
459 #ifdef MS_WIN32
460 "<cparam '%c' (%I64d)>",
461 #else
462 "<cparam '%c' (%qd)>",
463 #endif
464 self->tag, self->value.q);
465 break;
466 #endif
467 case 'd':
468 sprintf(buffer, "<cparam '%c' (%f)>",
469 self->tag, self->value.d);
470 break;
471 case 'f':
472 sprintf(buffer, "<cparam '%c' (%f)>",
473 self->tag, self->value.f);
474 break;
476 case 'c':
477 sprintf(buffer, "<cparam '%c' (%c)>",
478 self->tag, self->value.c);
479 break;
481 /* Hm, are these 'z' and 'Z' codes useful at all?
482 Shouldn't they be replaced by the functionality of c_string
483 and c_wstring ?
485 case 'z':
486 case 'Z':
487 case 'P':
488 sprintf(buffer, "<cparam '%c' (%p)>",
489 self->tag, self->value.p);
490 break;
492 default:
493 sprintf(buffer, "<cparam '%c' at %p>",
494 self->tag, self);
495 break;
497 return PyString_FromString(buffer);
500 static PyMemberDef PyCArgType_members[] = {
501 { "_obj", T_OBJECT,
502 offsetof(PyCArgObject, obj), READONLY,
503 "the wrapped object" },
504 { NULL },
507 PyTypeObject PyCArg_Type = {
508 PyVarObject_HEAD_INIT(NULL, 0)
509 "CArgObject",
510 sizeof(PyCArgObject),
512 (destructor)PyCArg_dealloc, /* tp_dealloc */
513 0, /* tp_print */
514 0, /* tp_getattr */
515 0, /* tp_setattr */
516 0, /* tp_compare */
517 (reprfunc)PyCArg_repr, /* tp_repr */
518 0, /* tp_as_number */
519 0, /* tp_as_sequence */
520 0, /* tp_as_mapping */
521 0, /* tp_hash */
522 0, /* tp_call */
523 0, /* tp_str */
524 0, /* tp_getattro */
525 0, /* tp_setattro */
526 0, /* tp_as_buffer */
527 Py_TPFLAGS_DEFAULT, /* tp_flags */
528 0, /* tp_doc */
529 0, /* tp_traverse */
530 0, /* tp_clear */
531 0, /* tp_richcompare */
532 0, /* tp_weaklistoffset */
533 0, /* tp_iter */
534 0, /* tp_iternext */
535 0, /* tp_methods */
536 PyCArgType_members, /* tp_members */
539 /****************************************************************/
541 * Convert a PyObject * into a parameter suitable to pass to an
542 * C function call.
544 * 1. Python integers are converted to C int and passed by value.
545 * Py_None is converted to a C NULL pointer.
547 * 2. 3-tuples are expected to have a format character in the first
548 * item, which must be 'i', 'f', 'd', 'q', or 'P'.
549 * The second item will have to be an integer, float, double, long long
550 * or integer (denoting an address void *), will be converted to the
551 * corresponding C data type and passed by value.
553 * 3. Other Python objects are tested for an '_as_parameter_' attribute.
554 * The value of this attribute must be an integer which will be passed
555 * by value, or a 2-tuple or 3-tuple which will be used according
556 * to point 2 above. The third item (if any), is ignored. It is normally
557 * used to keep the object alive where this parameter refers to.
558 * XXX This convention is dangerous - you can construct arbitrary tuples
559 * in Python and pass them. Would it be safer to use a custom container
560 * datatype instead of a tuple?
562 * 4. Other Python objects cannot be passed as parameters - an exception is raised.
564 * 5. ConvParam will store the converted result in a struct containing format
565 * and value.
568 union result {
569 char c;
570 char b;
571 short h;
572 int i;
573 long l;
574 #ifdef HAVE_LONG_LONG
575 PY_LONG_LONG q;
576 #endif
577 long double D;
578 double d;
579 float f;
580 void *p;
583 struct argument {
584 ffi_type *ffi_type;
585 PyObject *keep;
586 union result value;
590 * Convert a single Python object into a PyCArgObject and return it.
592 static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa)
594 StgDictObject *dict;
595 pa->keep = NULL; /* so we cannot forget it later */
597 dict = PyObject_stgdict(obj);
598 if (dict) {
599 PyCArgObject *carg;
600 assert(dict->paramfunc);
601 /* If it has an stgdict, it is a CDataObject */
602 carg = dict->paramfunc((CDataObject *)obj);
603 pa->ffi_type = carg->pffi_type;
604 memcpy(&pa->value, &carg->value, sizeof(pa->value));
605 pa->keep = (PyObject *)carg;
606 return 0;
609 if (PyCArg_CheckExact(obj)) {
610 PyCArgObject *carg = (PyCArgObject *)obj;
611 pa->ffi_type = carg->pffi_type;
612 Py_INCREF(obj);
613 pa->keep = obj;
614 memcpy(&pa->value, &carg->value, sizeof(pa->value));
615 return 0;
618 /* check for None, integer, string or unicode and use directly if successful */
619 if (obj == Py_None) {
620 pa->ffi_type = &ffi_type_pointer;
621 pa->value.p = NULL;
622 return 0;
625 if (PyInt_Check(obj)) {
626 pa->ffi_type = &ffi_type_sint;
627 pa->value.i = PyInt_AS_LONG(obj);
628 return 0;
631 if (PyLong_Check(obj)) {
632 pa->ffi_type = &ffi_type_sint;
633 pa->value.i = (long)PyLong_AsUnsignedLong(obj);
634 if (pa->value.i == -1 && PyErr_Occurred()) {
635 PyErr_Clear();
636 pa->value.i = PyLong_AsLong(obj);
637 if (pa->value.i == -1 && PyErr_Occurred()) {
638 PyErr_SetString(PyExc_OverflowError,
639 "long int too long to convert");
640 return -1;
643 return 0;
646 if (PyString_Check(obj)) {
647 pa->ffi_type = &ffi_type_pointer;
648 pa->value.p = PyString_AS_STRING(obj);
649 Py_INCREF(obj);
650 pa->keep = obj;
651 return 0;
654 #ifdef CTYPES_UNICODE
655 if (PyUnicode_Check(obj)) {
656 #ifdef HAVE_USABLE_WCHAR_T
657 pa->ffi_type = &ffi_type_pointer;
658 pa->value.p = PyUnicode_AS_UNICODE(obj);
659 Py_INCREF(obj);
660 pa->keep = obj;
661 return 0;
662 #else
663 int size = PyUnicode_GET_SIZE(obj);
664 pa->ffi_type = &ffi_type_pointer;
665 size += 1; /* terminating NUL */
666 size *= sizeof(wchar_t);
667 pa->value.p = PyMem_Malloc(size);
668 if (!pa->value.p) {
669 PyErr_NoMemory();
670 return -1;
672 memset(pa->value.p, 0, size);
673 pa->keep = PyCObject_FromVoidPtr(pa->value.p, PyMem_Free);
674 if (!pa->keep) {
675 PyMem_Free(pa->value.p);
676 return -1;
678 if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj,
679 pa->value.p, PyUnicode_GET_SIZE(obj)))
680 return -1;
681 return 0;
682 #endif
684 #endif
687 PyObject *arg;
688 arg = PyObject_GetAttrString(obj, "_as_parameter_");
689 /* Which types should we exactly allow here?
690 integers are required for using Python classes
691 as parameters (they have to expose the '_as_parameter_'
692 attribute)
694 if (arg) {
695 int result;
696 result = ConvParam(arg, index, pa);
697 Py_DECREF(arg);
698 return result;
700 PyErr_Format(PyExc_TypeError,
701 "Don't know how to convert parameter %d",
702 Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
703 return -1;
708 ffi_type *_ctypes_get_ffi_type(PyObject *obj)
710 StgDictObject *dict;
711 if (obj == NULL)
712 return &ffi_type_sint;
713 dict = PyType_stgdict(obj);
714 if (dict == NULL)
715 return &ffi_type_sint;
716 #if defined(MS_WIN32) && !defined(_WIN32_WCE)
717 /* This little trick works correctly with MSVC.
718 It returns small structures in registers
720 if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
721 if (dict->ffi_type_pointer.size <= 4)
722 return &ffi_type_sint32;
723 else if (dict->ffi_type_pointer.size <= 8)
724 return &ffi_type_sint64;
726 #endif
727 return &dict->ffi_type_pointer;
732 * libffi uses:
734 * ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi,
735 * unsigned int nargs,
736 * ffi_type *rtype,
737 * ffi_type **atypes);
739 * and then
741 * void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues);
743 static int _call_function_pointer(int flags,
744 PPROC pProc,
745 void **avalues,
746 ffi_type **atypes,
747 ffi_type *restype,
748 void *resmem,
749 int argcount)
751 #ifdef WITH_THREAD
752 PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
753 #endif
754 PyObject *error_object = NULL;
755 int *space;
756 ffi_cif cif;
757 int cc;
758 #ifdef MS_WIN32
759 int delta;
760 #ifndef DONT_USE_SEH
761 DWORD dwExceptionCode = 0;
762 EXCEPTION_RECORD record;
763 #endif
764 #endif
765 /* XXX check before here */
766 if (restype == NULL) {
767 PyErr_SetString(PyExc_RuntimeError,
768 "No ffi_type for result");
769 return -1;
772 cc = FFI_DEFAULT_ABI;
773 #if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE)
774 if ((flags & FUNCFLAG_CDECL) == 0)
775 cc = FFI_STDCALL;
776 #endif
777 if (FFI_OK != ffi_prep_cif(&cif,
779 argcount,
780 restype,
781 atypes)) {
782 PyErr_SetString(PyExc_RuntimeError,
783 "ffi_prep_cif failed");
784 return -1;
787 if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
788 error_object = _ctypes_get_errobj(&space);
789 if (error_object == NULL)
790 return -1;
792 #ifdef WITH_THREAD
793 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
794 Py_UNBLOCK_THREADS
795 #endif
796 if (flags & FUNCFLAG_USE_ERRNO) {
797 int temp = space[0];
798 space[0] = errno;
799 errno = temp;
801 #ifdef MS_WIN32
802 if (flags & FUNCFLAG_USE_LASTERROR) {
803 int temp = space[1];
804 space[1] = GetLastError();
805 SetLastError(temp);
807 #ifndef DONT_USE_SEH
808 __try {
809 #endif
810 delta =
811 #endif
812 ffi_call(&cif, (void *)pProc, resmem, avalues);
813 #ifdef MS_WIN32
814 #ifndef DONT_USE_SEH
816 __except (HandleException(GetExceptionInformation(),
817 &dwExceptionCode, &record)) {
820 #endif
821 if (flags & FUNCFLAG_USE_LASTERROR) {
822 int temp = space[1];
823 space[1] = GetLastError();
824 SetLastError(temp);
826 #endif
827 if (flags & FUNCFLAG_USE_ERRNO) {
828 int temp = space[0];
829 space[0] = errno;
830 errno = temp;
832 Py_XDECREF(error_object);
833 #ifdef WITH_THREAD
834 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
835 Py_BLOCK_THREADS
836 #endif
837 #ifdef MS_WIN32
838 #ifndef DONT_USE_SEH
839 if (dwExceptionCode) {
840 SetException(dwExceptionCode, &record);
841 return -1;
843 #endif
844 #ifdef MS_WIN64
845 if (delta != 0) {
846 PyErr_Format(PyExc_RuntimeError,
847 "ffi_call failed with code %d",
848 delta);
849 return -1;
851 #else
852 if (delta < 0) {
853 if (flags & FUNCFLAG_CDECL)
854 PyErr_Format(PyExc_ValueError,
855 "Procedure called with not enough "
856 "arguments (%d bytes missing) "
857 "or wrong calling convention",
858 -delta);
859 else
860 PyErr_Format(PyExc_ValueError,
861 "Procedure probably called with not enough "
862 "arguments (%d bytes missing)",
863 -delta);
864 return -1;
865 } else if (delta > 0) {
866 PyErr_Format(PyExc_ValueError,
867 "Procedure probably called with too many "
868 "arguments (%d bytes in excess)",
869 delta);
870 return -1;
872 #endif
873 #endif
874 if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
875 return -1;
876 return 0;
880 * Convert the C value in result into a Python object, depending on restype.
882 * - If restype is NULL, return a Python integer.
883 * - If restype is None, return None.
884 * - If restype is a simple ctypes type (c_int, c_void_p), call the type's getfunc,
885 * pass the result to checker and return the result.
886 * - If restype is another ctypes type, return an instance of that.
887 * - Otherwise, call restype and return the result.
889 static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker)
891 StgDictObject *dict;
892 PyObject *retval, *v;
894 if (restype == NULL)
895 return PyInt_FromLong(*(int *)result);
897 if (restype == Py_None) {
898 Py_INCREF(Py_None);
899 return Py_None;
902 dict = PyType_stgdict(restype);
903 if (dict == NULL)
904 return PyObject_CallFunction(restype, "i", *(int *)result);
906 if (dict->getfunc && !_ctypes_simple_instance(restype)) {
907 retval = dict->getfunc(result, dict->size);
908 /* If restype is py_object (detected by comparing getfunc with
909 O_get), we have to call Py_DECREF because O_get has already
910 called Py_INCREF.
912 if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
913 Py_DECREF(retval);
915 } else
916 retval = PyCData_FromBaseObj(restype, NULL, 0, result);
918 if (!checker || !retval)
919 return retval;
921 v = PyObject_CallFunctionObjArgs(checker, retval, NULL);
922 if (v == NULL)
923 _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2);
924 Py_DECREF(retval);
925 return v;
929 * Raise a new exception 'exc_class', adding additional text to the original
930 * exception string.
932 void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...)
934 va_list vargs;
935 PyObject *tp, *v, *tb, *s, *cls_str, *msg_str;
937 va_start(vargs, fmt);
938 s = PyString_FromFormatV(fmt, vargs);
939 va_end(vargs);
940 if (!s)
941 return;
943 PyErr_Fetch(&tp, &v, &tb);
944 PyErr_NormalizeException(&tp, &v, &tb);
945 cls_str = PyObject_Str(tp);
946 if (cls_str) {
947 PyString_ConcatAndDel(&s, cls_str);
948 PyString_ConcatAndDel(&s, PyString_FromString(": "));
949 if (s == NULL)
950 goto error;
951 } else
952 PyErr_Clear();
953 msg_str = PyObject_Str(v);
954 if (msg_str)
955 PyString_ConcatAndDel(&s, msg_str);
956 else {
957 PyErr_Clear();
958 PyString_ConcatAndDel(&s, PyString_FromString("???"));
959 if (s == NULL)
960 goto error;
962 PyErr_SetObject(exc_class, s);
963 error:
964 Py_XDECREF(tp);
965 Py_XDECREF(v);
966 Py_XDECREF(tb);
967 Py_XDECREF(s);
971 #ifdef MS_WIN32
973 static PyObject *
974 GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk)
976 HRESULT hr;
977 ISupportErrorInfo *psei = NULL;
978 IErrorInfo *pei = NULL;
979 BSTR descr=NULL, helpfile=NULL, source=NULL;
980 GUID guid;
981 DWORD helpcontext=0;
982 LPOLESTR progid;
983 PyObject *obj;
984 TCHAR *text;
986 /* We absolutely have to release the GIL during COM method calls,
987 otherwise we may get a deadlock!
989 #ifdef WITH_THREAD
990 Py_BEGIN_ALLOW_THREADS
991 #endif
993 hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei);
994 if (FAILED(hr))
995 goto failed;
997 hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid);
998 psei->lpVtbl->Release(psei);
999 if (FAILED(hr))
1000 goto failed;
1002 hr = GetErrorInfo(0, &pei);
1003 if (hr != S_OK)
1004 goto failed;
1006 pei->lpVtbl->GetDescription(pei, &descr);
1007 pei->lpVtbl->GetGUID(pei, &guid);
1008 pei->lpVtbl->GetHelpContext(pei, &helpcontext);
1009 pei->lpVtbl->GetHelpFile(pei, &helpfile);
1010 pei->lpVtbl->GetSource(pei, &source);
1012 pei->lpVtbl->Release(pei);
1014 failed:
1015 #ifdef WITH_THREAD
1016 Py_END_ALLOW_THREADS
1017 #endif
1019 progid = NULL;
1020 ProgIDFromCLSID(&guid, &progid);
1022 text = FormatError(errcode);
1023 obj = Py_BuildValue(
1024 #ifdef _UNICODE
1025 "iu(uuuiu)",
1026 #else
1027 "is(uuuiu)",
1028 #endif
1029 errcode,
1030 text,
1031 descr, source, helpfile, helpcontext,
1032 progid);
1033 if (obj) {
1034 PyErr_SetObject(ComError, obj);
1035 Py_DECREF(obj);
1037 LocalFree(text);
1039 if (descr)
1040 SysFreeString(descr);
1041 if (helpfile)
1042 SysFreeString(helpfile);
1043 if (source)
1044 SysFreeString(source);
1046 return NULL;
1048 #endif
1051 * Requirements, must be ensured by the caller:
1052 * - argtuple is tuple of arguments
1053 * - argtypes is either NULL, or a tuple of the same size as argtuple
1055 * - XXX various requirements for restype, not yet collected
1057 PyObject *_ctypes_callproc(PPROC pProc,
1058 PyObject *argtuple,
1059 #ifdef MS_WIN32
1060 IUnknown *pIunk,
1061 GUID *iid,
1062 #endif
1063 int flags,
1064 PyObject *argtypes, /* misleading name: This is a tuple of
1065 methods, not types: the .from_param
1066 class methods of the types */
1067 PyObject *restype,
1068 PyObject *checker)
1070 Py_ssize_t i, n, argcount, argtype_count;
1071 void *resbuf;
1072 struct argument *args, *pa;
1073 ffi_type **atypes;
1074 ffi_type *rtype;
1075 void **avalues;
1076 PyObject *retval = NULL;
1078 n = argcount = PyTuple_GET_SIZE(argtuple);
1079 #ifdef MS_WIN32
1080 /* an optional COM object this pointer */
1081 if (pIunk)
1082 ++argcount;
1083 #endif
1085 args = (struct argument *)alloca(sizeof(struct argument) * argcount);
1086 if (!args) {
1087 PyErr_NoMemory();
1088 return NULL;
1090 memset(args, 0, sizeof(struct argument) * argcount);
1091 argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
1092 #ifdef MS_WIN32
1093 if (pIunk) {
1094 args[0].ffi_type = &ffi_type_pointer;
1095 args[0].value.p = pIunk;
1096 pa = &args[1];
1097 } else
1098 #endif
1099 pa = &args[0];
1101 /* Convert the arguments */
1102 for (i = 0; i < n; ++i, ++pa) {
1103 PyObject *converter;
1104 PyObject *arg;
1105 int err;
1107 arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */
1108 /* For cdecl functions, we allow more actual arguments
1109 than the length of the argtypes tuple.
1110 This is checked in _ctypes::PyCFuncPtr_Call
1112 if (argtypes && argtype_count > i) {
1113 PyObject *v;
1114 converter = PyTuple_GET_ITEM(argtypes, i);
1115 v = PyObject_CallFunctionObjArgs(converter,
1116 arg,
1117 NULL);
1118 if (v == NULL) {
1119 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1120 goto cleanup;
1123 err = ConvParam(v, i+1, pa);
1124 Py_DECREF(v);
1125 if (-1 == err) {
1126 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1127 goto cleanup;
1129 } else {
1130 err = ConvParam(arg, i+1, pa);
1131 if (-1 == err) {
1132 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1133 goto cleanup; /* leaking ? */
1138 rtype = _ctypes_get_ffi_type(restype);
1139 resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));
1141 avalues = (void **)alloca(sizeof(void *) * argcount);
1142 atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
1143 if (!resbuf || !avalues || !atypes) {
1144 PyErr_NoMemory();
1145 goto cleanup;
1147 for (i = 0; i < argcount; ++i) {
1148 atypes[i] = args[i].ffi_type;
1149 if (atypes[i]->type == FFI_TYPE_STRUCT
1150 #ifdef _WIN64
1151 && atypes[i]->size <= sizeof(void *)
1152 #endif
1154 avalues[i] = (void *)args[i].value.p;
1155 else
1156 avalues[i] = (void *)&args[i].value;
1159 if (-1 == _call_function_pointer(flags, pProc, avalues, atypes,
1160 rtype, resbuf,
1161 Py_SAFE_DOWNCAST(argcount,
1162 Py_ssize_t,
1163 int)))
1164 goto cleanup;
1166 #ifdef WORDS_BIGENDIAN
1167 /* libffi returns the result in a buffer with sizeof(ffi_arg). This
1168 causes problems on big endian machines, since the result buffer
1169 address cannot simply be used as result pointer, instead we must
1170 adjust the pointer value:
1173 XXX I should find out and clarify why this is needed at all,
1174 especially why adjusting for ffi_type_float must be avoided on
1175 64-bit platforms.
1177 if (rtype->type != FFI_TYPE_FLOAT
1178 && rtype->type != FFI_TYPE_STRUCT
1179 && rtype->size < sizeof(ffi_arg))
1180 resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
1181 #endif
1183 #ifdef MS_WIN32
1184 if (iid && pIunk) {
1185 if (*(int *)resbuf & 0x80000000)
1186 retval = GetComError(*(HRESULT *)resbuf, iid, pIunk);
1187 else
1188 retval = PyInt_FromLong(*(int *)resbuf);
1189 } else if (flags & FUNCFLAG_HRESULT) {
1190 if (*(int *)resbuf & 0x80000000)
1191 retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
1192 else
1193 retval = PyInt_FromLong(*(int *)resbuf);
1194 } else
1195 #endif
1196 retval = GetResult(restype, resbuf, checker);
1197 cleanup:
1198 for (i = 0; i < argcount; ++i)
1199 Py_XDECREF(args[i].keep);
1200 return retval;
1203 static int
1204 _parse_voidp(PyObject *obj, void **address)
1206 *address = PyLong_AsVoidPtr(obj);
1207 if (*address == NULL)
1208 return 0;
1209 return 1;
1212 #ifdef MS_WIN32
1214 #ifdef _UNICODE
1215 # define PYBUILD_TSTR "u"
1216 #else
1217 # define PYBUILD_TSTR "s"
1218 # ifndef _T
1219 # define _T(text) text
1220 # endif
1221 #endif
1223 static char format_error_doc[] =
1224 "FormatError([integer]) -> string\n\
1226 Convert a win32 error code into a string. If the error code is not\n\
1227 given, the return value of a call to GetLastError() is used.\n";
1228 static PyObject *format_error(PyObject *self, PyObject *args)
1230 PyObject *result;
1231 TCHAR *lpMsgBuf;
1232 DWORD code = 0;
1233 if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
1234 return NULL;
1235 if (code == 0)
1236 code = GetLastError();
1237 lpMsgBuf = FormatError(code);
1238 if (lpMsgBuf) {
1239 result = Py_BuildValue(PYBUILD_TSTR, lpMsgBuf);
1240 LocalFree(lpMsgBuf);
1241 } else {
1242 result = Py_BuildValue("s", "<no description>");
1244 return result;
1247 static char load_library_doc[] =
1248 "LoadLibrary(name) -> handle\n\
1250 Load an executable (usually a DLL), and return a handle to it.\n\
1251 The handle may be used to locate exported functions in this\n\
1252 module.\n";
1253 static PyObject *load_library(PyObject *self, PyObject *args)
1255 TCHAR *name;
1256 PyObject *nameobj;
1257 PyObject *ignored;
1258 HMODULE hMod;
1259 if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
1260 return NULL;
1261 #ifdef _UNICODE
1262 name = alloca((PyString_Size(nameobj) + 1) * sizeof(WCHAR));
1263 if (!name) {
1264 PyErr_NoMemory();
1265 return NULL;
1269 int r;
1270 char *aname = PyString_AsString(nameobj);
1271 if(!aname)
1272 return NULL;
1273 r = MultiByteToWideChar(CP_ACP, 0, aname, -1, name, PyString_Size(nameobj) + 1);
1274 name[r] = 0;
1276 #else
1277 name = PyString_AsString(nameobj);
1278 if(!name)
1279 return NULL;
1280 #endif
1282 hMod = LoadLibrary(name);
1283 if (!hMod)
1284 return PyErr_SetFromWindowsErr(GetLastError());
1285 #ifdef _WIN64
1286 return PyLong_FromVoidPtr(hMod);
1287 #else
1288 return Py_BuildValue("i", hMod);
1289 #endif
1292 static char free_library_doc[] =
1293 "FreeLibrary(handle) -> void\n\
1295 Free the handle of an executable previously loaded by LoadLibrary.\n";
1296 static PyObject *free_library(PyObject *self, PyObject *args)
1298 void *hMod;
1299 if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
1300 return NULL;
1301 if (!FreeLibrary((HMODULE)hMod))
1302 return PyErr_SetFromWindowsErr(GetLastError());
1303 Py_INCREF(Py_None);
1304 return Py_None;
1307 /* obsolete, should be removed */
1308 /* Only used by sample code (in samples\Windows\COM.py) */
1309 static PyObject *
1310 call_commethod(PyObject *self, PyObject *args)
1312 IUnknown *pIunk;
1313 int index;
1314 PyObject *arguments;
1315 PPROC *lpVtbl;
1316 PyObject *result;
1317 CDataObject *pcom;
1318 PyObject *argtypes = NULL;
1320 if (!PyArg_ParseTuple(args,
1321 "OiO!|O!",
1322 &pcom, &index,
1323 &PyTuple_Type, &arguments,
1324 &PyTuple_Type, &argtypes))
1325 return NULL;
1327 if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) {
1328 PyErr_Format(PyExc_TypeError,
1329 "Method takes %d arguments (%d given)",
1330 PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments));
1331 return NULL;
1334 if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) {
1335 PyErr_Format(PyExc_TypeError,
1336 "COM Pointer expected instead of %s instance",
1337 Py_TYPE(pcom)->tp_name);
1338 return NULL;
1341 if ((*(void **)(pcom->b_ptr)) == NULL) {
1342 PyErr_SetString(PyExc_ValueError,
1343 "The COM 'this' pointer is NULL");
1344 return NULL;
1347 pIunk = (IUnknown *)(*(void **)(pcom->b_ptr));
1348 lpVtbl = (PPROC *)(pIunk->lpVtbl);
1350 result = _ctypes_callproc(lpVtbl[index],
1351 arguments,
1352 #ifdef MS_WIN32
1353 pIunk,
1354 NULL,
1355 #endif
1356 FUNCFLAG_HRESULT, /* flags */
1357 argtypes, /* self->argtypes */
1358 NULL, /* self->restype */
1359 NULL); /* checker */
1360 return result;
1363 static char copy_com_pointer_doc[] =
1364 "CopyComPointer(src, dst) -> HRESULT value\n";
1366 static PyObject *
1367 copy_com_pointer(PyObject *self, PyObject *args)
1369 PyObject *p1, *p2, *r = NULL;
1370 struct argument a, b;
1371 IUnknown *src, **pdst;
1372 if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
1373 return NULL;
1374 a.keep = b.keep = NULL;
1376 if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b))
1377 goto done;
1378 src = (IUnknown *)a.value.p;
1379 pdst = (IUnknown **)b.value.p;
1381 if (pdst == NULL)
1382 r = PyInt_FromLong(E_POINTER);
1383 else {
1384 if (src)
1385 src->lpVtbl->AddRef(src);
1386 *pdst = src;
1387 r = PyInt_FromLong(S_OK);
1389 done:
1390 Py_XDECREF(a.keep);
1391 Py_XDECREF(b.keep);
1392 return r;
1394 #else
1396 static PyObject *py_dl_open(PyObject *self, PyObject *args)
1398 char *name;
1399 void * handle;
1400 #ifdef RTLD_LOCAL
1401 int mode = RTLD_NOW | RTLD_LOCAL;
1402 #else
1403 /* cygwin doesn't define RTLD_LOCAL */
1404 int mode = RTLD_NOW;
1405 #endif
1406 if (!PyArg_ParseTuple(args, "z|i:dlopen", &name, &mode))
1407 return NULL;
1408 mode |= RTLD_NOW;
1409 handle = ctypes_dlopen(name, mode);
1410 if (!handle) {
1411 char *errmsg = ctypes_dlerror();
1412 if (!errmsg)
1413 errmsg = "dlopen() error";
1414 PyErr_SetString(PyExc_OSError,
1415 errmsg);
1416 return NULL;
1418 return PyLong_FromVoidPtr(handle);
1421 static PyObject *py_dl_close(PyObject *self, PyObject *args)
1423 void *handle;
1425 if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
1426 return NULL;
1427 if (dlclose(handle)) {
1428 PyErr_SetString(PyExc_OSError,
1429 ctypes_dlerror());
1430 return NULL;
1432 Py_INCREF(Py_None);
1433 return Py_None;
1436 static PyObject *py_dl_sym(PyObject *self, PyObject *args)
1438 char *name;
1439 void *handle;
1440 void *ptr;
1442 if (!PyArg_ParseTuple(args, "O&s:dlsym",
1443 &_parse_voidp, &handle, &name))
1444 return NULL;
1445 ptr = ctypes_dlsym((void*)handle, name);
1446 if (!ptr) {
1447 PyErr_SetString(PyExc_OSError,
1448 ctypes_dlerror());
1449 return NULL;
1451 return PyLong_FromVoidPtr(ptr);
1453 #endif
1456 * Only for debugging so far: So that we can call CFunction instances
1458 * XXX Needs to accept more arguments: flags, argtypes, restype
1460 static PyObject *
1461 call_function(PyObject *self, PyObject *args)
1463 void *func;
1464 PyObject *arguments;
1465 PyObject *result;
1467 if (!PyArg_ParseTuple(args,
1468 "O&O!",
1469 &_parse_voidp, &func,
1470 &PyTuple_Type, &arguments))
1471 return NULL;
1473 result = _ctypes_callproc((PPROC)func,
1474 arguments,
1475 #ifdef MS_WIN32
1476 NULL,
1477 NULL,
1478 #endif
1479 0, /* flags */
1480 NULL, /* self->argtypes */
1481 NULL, /* self->restype */
1482 NULL); /* checker */
1483 return result;
1487 * Only for debugging so far: So that we can call CFunction instances
1489 * XXX Needs to accept more arguments: flags, argtypes, restype
1491 static PyObject *
1492 call_cdeclfunction(PyObject *self, PyObject *args)
1494 void *func;
1495 PyObject *arguments;
1496 PyObject *result;
1498 if (!PyArg_ParseTuple(args,
1499 "O&O!",
1500 &_parse_voidp, &func,
1501 &PyTuple_Type, &arguments))
1502 return NULL;
1504 result = _ctypes_callproc((PPROC)func,
1505 arguments,
1506 #ifdef MS_WIN32
1507 NULL,
1508 NULL,
1509 #endif
1510 FUNCFLAG_CDECL, /* flags */
1511 NULL, /* self->argtypes */
1512 NULL, /* self->restype */
1513 NULL); /* checker */
1514 return result;
1517 /*****************************************************************
1518 * functions
1520 static char sizeof_doc[] =
1521 "sizeof(C type) -> integer\n"
1522 "sizeof(C instance) -> integer\n"
1523 "Return the size in bytes of a C instance";
1525 static PyObject *
1526 sizeof_func(PyObject *self, PyObject *obj)
1528 StgDictObject *dict;
1530 dict = PyType_stgdict(obj);
1531 if (dict)
1532 return PyInt_FromSsize_t(dict->size);
1534 if (CDataObject_Check(obj))
1535 return PyInt_FromSsize_t(((CDataObject *)obj)->b_size);
1536 PyErr_SetString(PyExc_TypeError,
1537 "this type has no size");
1538 return NULL;
1541 static char alignment_doc[] =
1542 "alignment(C type) -> integer\n"
1543 "alignment(C instance) -> integer\n"
1544 "Return the alignment requirements of a C instance";
1546 static PyObject *
1547 align_func(PyObject *self, PyObject *obj)
1549 StgDictObject *dict;
1551 dict = PyType_stgdict(obj);
1552 if (dict)
1553 return PyInt_FromSsize_t(dict->align);
1555 dict = PyObject_stgdict(obj);
1556 if (dict)
1557 return PyInt_FromSsize_t(dict->align);
1559 PyErr_SetString(PyExc_TypeError,
1560 "no alignment info");
1561 return NULL;
1564 static char byref_doc[] =
1565 "byref(C instance[, offset=0]) -> byref-object\n"
1566 "Return a pointer lookalike to a C instance, only usable\n"
1567 "as function argument";
1570 * We must return something which can be converted to a parameter,
1571 * but still has a reference to self.
1573 static PyObject *
1574 byref(PyObject *self, PyObject *args)
1576 PyCArgObject *parg;
1577 PyObject *obj;
1578 PyObject *pyoffset = NULL;
1579 Py_ssize_t offset = 0;
1581 if (!PyArg_UnpackTuple(args, "byref", 1, 2,
1582 &obj, &pyoffset))
1583 return NULL;
1584 if (pyoffset) {
1585 offset = PyNumber_AsSsize_t(pyoffset, NULL);
1586 if (offset == -1 && PyErr_Occurred())
1587 return NULL;
1589 if (!CDataObject_Check(obj)) {
1590 PyErr_Format(PyExc_TypeError,
1591 "byref() argument must be a ctypes instance, not '%s'",
1592 Py_TYPE(obj)->tp_name);
1593 return NULL;
1596 parg = PyCArgObject_new();
1597 if (parg == NULL)
1598 return NULL;
1600 parg->tag = 'P';
1601 parg->pffi_type = &ffi_type_pointer;
1602 Py_INCREF(obj);
1603 parg->obj = obj;
1604 parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
1605 return (PyObject *)parg;
1608 static char addressof_doc[] =
1609 "addressof(C instance) -> integer\n"
1610 "Return the address of the C instance internal buffer";
1612 static PyObject *
1613 addressof(PyObject *self, PyObject *obj)
1615 if (CDataObject_Check(obj))
1616 return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
1617 PyErr_SetString(PyExc_TypeError,
1618 "invalid type");
1619 return NULL;
1622 static int
1623 converter(PyObject *obj, void **address)
1625 *address = PyLong_AsVoidPtr(obj);
1626 return *address != NULL;
1629 static PyObject *
1630 My_PyObj_FromPtr(PyObject *self, PyObject *args)
1632 PyObject *ob;
1633 if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob))
1634 return NULL;
1635 Py_INCREF(ob);
1636 return ob;
1639 static PyObject *
1640 My_Py_INCREF(PyObject *self, PyObject *arg)
1642 Py_INCREF(arg); /* that's what this function is for */
1643 Py_INCREF(arg); /* that for returning it */
1644 return arg;
1647 static PyObject *
1648 My_Py_DECREF(PyObject *self, PyObject *arg)
1650 Py_DECREF(arg); /* that's what this function is for */
1651 Py_INCREF(arg); /* that's for returning it */
1652 return arg;
1655 #ifdef CTYPES_UNICODE
1657 static char set_conversion_mode_doc[] =
1658 "set_conversion_mode(encoding, errors) -> (previous-encoding, previous-errors)\n\
1660 Set the encoding and error handling ctypes uses when converting\n\
1661 between unicode and strings. Returns the previous values.\n";
1663 static PyObject *
1664 set_conversion_mode(PyObject *self, PyObject *args)
1666 char *coding, *mode;
1667 PyObject *result;
1669 if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode))
1670 return NULL;
1671 result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors);
1672 if (coding) {
1673 PyMem_Free(_ctypes_conversion_encoding);
1674 _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1);
1675 strcpy(_ctypes_conversion_encoding, coding);
1676 } else {
1677 _ctypes_conversion_encoding = NULL;
1679 PyMem_Free(_ctypes_conversion_errors);
1680 _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1);
1681 strcpy(_ctypes_conversion_errors, mode);
1682 return result;
1684 #endif
1686 static PyObject *
1687 resize(PyObject *self, PyObject *args)
1689 CDataObject *obj;
1690 StgDictObject *dict;
1691 Py_ssize_t size;
1693 if (!PyArg_ParseTuple(args,
1694 #if (PY_VERSION_HEX < 0x02050000)
1695 "Oi:resize",
1696 #else
1697 "On:resize",
1698 #endif
1699 &obj, &size))
1700 return NULL;
1702 dict = PyObject_stgdict((PyObject *)obj);
1703 if (dict == NULL) {
1704 PyErr_SetString(PyExc_TypeError,
1705 "excepted ctypes instance");
1706 return NULL;
1708 if (size < dict->size) {
1709 PyErr_Format(PyExc_ValueError,
1710 #if PY_VERSION_HEX < 0x02050000
1711 "minimum size is %d",
1712 #else
1713 "minimum size is %zd",
1714 #endif
1715 dict->size);
1716 return NULL;
1718 if (obj->b_needsfree == 0) {
1719 PyErr_Format(PyExc_ValueError,
1720 "Memory cannot be resized because this object doesn't own it");
1721 return NULL;
1723 if (size <= sizeof(obj->b_value)) {
1724 /* internal default buffer is large enough */
1725 obj->b_size = size;
1726 goto done;
1728 if (obj->b_size <= sizeof(obj->b_value)) {
1729 /* We are currently using the objects default buffer, but it
1730 isn't large enough any more. */
1731 void *ptr = PyMem_Malloc(size);
1732 if (ptr == NULL)
1733 return PyErr_NoMemory();
1734 memset(ptr, 0, size);
1735 memmove(ptr, obj->b_ptr, obj->b_size);
1736 obj->b_ptr = ptr;
1737 obj->b_size = size;
1738 } else {
1739 void * ptr = PyMem_Realloc(obj->b_ptr, size);
1740 if (ptr == NULL)
1741 return PyErr_NoMemory();
1742 obj->b_ptr = ptr;
1743 obj->b_size = size;
1745 done:
1746 Py_INCREF(Py_None);
1747 return Py_None;
1750 static PyObject *
1751 unpickle(PyObject *self, PyObject *args)
1753 PyObject *typ;
1754 PyObject *state;
1755 PyObject *result;
1756 PyObject *tmp;
1758 if (!PyArg_ParseTuple(args, "OO", &typ, &state))
1759 return NULL;
1760 result = PyObject_CallMethod(typ, "__new__", "O", typ);
1761 if (result == NULL)
1762 return NULL;
1763 tmp = PyObject_CallMethod(result, "__setstate__", "O", state);
1764 if (tmp == NULL) {
1765 Py_DECREF(result);
1766 return NULL;
1768 Py_DECREF(tmp);
1769 return result;
1772 static PyObject *
1773 POINTER(PyObject *self, PyObject *cls)
1775 PyObject *result;
1776 PyTypeObject *typ;
1777 PyObject *key;
1778 char *buf;
1780 result = PyDict_GetItem(_ctypes_ptrtype_cache, cls);
1781 if (result) {
1782 Py_INCREF(result);
1783 return result;
1785 if (PyString_CheckExact(cls)) {
1786 buf = alloca(strlen(PyString_AS_STRING(cls)) + 3 + 1);
1787 sprintf(buf, "LP_%s", PyString_AS_STRING(cls));
1788 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
1789 "s(O){}",
1790 buf,
1791 &PyCPointer_Type);
1792 if (result == NULL)
1793 return result;
1794 key = PyLong_FromVoidPtr(result);
1795 } else if (PyType_Check(cls)) {
1796 typ = (PyTypeObject *)cls;
1797 buf = alloca(strlen(typ->tp_name) + 3 + 1);
1798 sprintf(buf, "LP_%s", typ->tp_name);
1799 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
1800 "s(O){sO}",
1801 buf,
1802 &PyCPointer_Type,
1803 "_type_", cls);
1804 if (result == NULL)
1805 return result;
1806 Py_INCREF(cls);
1807 key = cls;
1808 } else {
1809 PyErr_SetString(PyExc_TypeError, "must be a ctypes type");
1810 return NULL;
1812 if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) {
1813 Py_DECREF(result);
1814 Py_DECREF(key);
1815 return NULL;
1817 Py_DECREF(key);
1818 return result;
1821 static PyObject *
1822 pointer(PyObject *self, PyObject *arg)
1824 PyObject *result;
1825 PyObject *typ;
1827 typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg));
1828 if (typ)
1829 return PyObject_CallFunctionObjArgs(typ, arg, NULL);
1830 typ = POINTER(NULL, (PyObject *)Py_TYPE(arg));
1831 if (typ == NULL)
1832 return NULL;
1833 result = PyObject_CallFunctionObjArgs(typ, arg, NULL);
1834 Py_DECREF(typ);
1835 return result;
1838 static PyObject *
1839 buffer_info(PyObject *self, PyObject *arg)
1841 StgDictObject *dict = PyType_stgdict(arg);
1842 PyObject *shape;
1843 Py_ssize_t i;
1845 if (dict == NULL)
1846 dict = PyObject_stgdict(arg);
1847 if (dict == NULL) {
1848 PyErr_SetString(PyExc_TypeError,
1849 "not a ctypes type or object");
1850 return NULL;
1852 shape = PyTuple_New(dict->ndim);
1853 if (shape == NULL)
1854 return NULL;
1855 for (i = 0; i < (int)dict->ndim; ++i)
1856 PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i]));
1858 if (PyErr_Occurred()) {
1859 Py_DECREF(shape);
1860 return NULL;
1862 return Py_BuildValue("siN", dict->format, dict->ndim, shape);
1865 PyMethodDef _ctypes_module_methods[] = {
1866 {"get_errno", get_errno, METH_NOARGS},
1867 {"set_errno", set_errno, METH_VARARGS},
1868 {"POINTER", POINTER, METH_O },
1869 {"pointer", pointer, METH_O },
1870 {"_unpickle", unpickle, METH_VARARGS },
1871 {"_buffer_info", buffer_info, METH_O,
1872 "Return buffer interface information (for testing only)"},
1873 {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
1874 #ifdef CTYPES_UNICODE
1875 {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc},
1876 #endif
1877 #ifdef MS_WIN32
1878 {"get_last_error", get_last_error, METH_NOARGS},
1879 {"set_last_error", set_last_error, METH_VARARGS},
1880 {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
1881 {"FormatError", format_error, METH_VARARGS, format_error_doc},
1882 {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
1883 {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
1884 {"call_commethod", call_commethod, METH_VARARGS },
1885 {"_check_HRESULT", check_hresult, METH_VARARGS},
1886 #else
1887 {"dlopen", py_dl_open, METH_VARARGS,
1888 "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
1889 {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
1890 {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
1891 #endif
1892 {"alignment", align_func, METH_O, alignment_doc},
1893 {"sizeof", sizeof_func, METH_O, sizeof_doc},
1894 {"byref", byref, METH_VARARGS, byref_doc},
1895 {"addressof", addressof, METH_O, addressof_doc},
1896 {"call_function", call_function, METH_VARARGS },
1897 {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
1898 {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
1899 {"Py_INCREF", My_Py_INCREF, METH_O },
1900 {"Py_DECREF", My_Py_DECREF, METH_O },
1901 {NULL, NULL} /* Sentinel */
1905 Local Variables:
1906 compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"
1907 End: