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