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