blob: 0e4f1b145ee5601dc6ffad01bc86bebe67f64a57 [file] [log] [blame]
Thomas Hellerd4c93202006-03-08 19:35:11 +00001/*
2 * History: First version dated from 3/97, derived from my SCMLIB version
3 * for win16.
4 */
5/*
6 * Related Work:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00007 * - calldll http://www.nightmare.com/software.html
8 * - libffi http://sourceware.cygnus.com/libffi/
9 * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html
Thomas Hellerd4c93202006-03-08 19:35:11 +000010 * and, of course, Don Beaudry's MESS package, but this is more ctypes
11 * related.
12 */
13
14
15/*
16 How are functions called, and how are parameters converted to C ?
17
Thomas Heller34596a92009-04-24 20:50:00 +000018 1. _ctypes.c::PyCFuncPtr_call receives an argument tuple 'inargs' and a
Thomas Hellerd4c93202006-03-08 19:35:11 +000019 keyword dictionary 'kwds'.
20
21 2. After several checks, _build_callargs() is called which returns another
22 tuple 'callargs'. This may be the same tuple as 'inargs', a slice of
23 'inargs', or a completely fresh tuple, depending on several things (is is a
24 COM method, are 'paramflags' available).
25
26 3. _build_callargs also calculates bitarrays containing indexes into
27 the callargs tuple, specifying how to build the return value(s) of
28 the function.
29
Thomas Heller34596a92009-04-24 20:50:00 +000030 4. _ctypes_callproc is then called with the 'callargs' tuple. _ctypes_callproc first
Thomas Hellerd4c93202006-03-08 19:35:11 +000031 allocates two arrays. The first is an array of 'struct argument' items, the
32 second array has 'void *' entried.
33
34 5. If 'converters' are present (converters is a sequence of argtypes'
35 from_param methods), for each item in 'callargs' converter is called and the
36 result passed to ConvParam. If 'converters' are not present, each argument
37 is directly passed to ConvParm.
38
39 6. For each arg, ConvParam stores the contained C data (or a pointer to it,
40 for structures) into the 'struct argument' array.
41
42 7. Finally, a loop fills the 'void *' array so that each item points to the
43 data contained in or pointed to by the 'struct argument' array.
44
45 8. The 'void *' argument array is what _call_function_pointer
46 expects. _call_function_pointer then has very little to do - only some
47 libffi specific stuff, then it calls ffi_call.
48
49 So, there are 4 data structures holding processed arguments:
Thomas Heller34596a92009-04-24 20:50:00 +000050 - the inargs tuple (in PyCFuncPtr_call)
51 - the callargs tuple (in PyCFuncPtr_call)
Thomas Hellerd4c93202006-03-08 19:35:11 +000052 - the 'struct argguments' array
53 - the 'void *' array
54
55 */
56
57#include "Python.h"
58#include "structmember.h"
59
60#ifdef MS_WIN32
61#include <windows.h>
Guido van Rossumd8faa362007-04-27 19:54:29 +000062#include <tchar.h>
Thomas Hellerd4c93202006-03-08 19:35:11 +000063#else
64#include "ctypes_dlfcn.h"
65#endif
66
67#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068#include <malloc.h>
Thomas Hellerd4c93202006-03-08 19:35:11 +000069#endif
70
71#include <ffi.h>
72#include "ctypes.h"
73
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000074#if defined(_DEBUG) || defined(__MINGW32__)
75/* Don't use structured exception handling on Windows if this is defined.
76 MingW, AFAIK, doesn't support it.
77*/
78#define DONT_USE_SEH
Thomas Hellerd4c93202006-03-08 19:35:11 +000079#endif
80
Benjamin Petersonb173f782009-05-05 22:31:58 +000081#define CTYPES_CAPSULE_NAME_PYMEM "_ctypes pymem"
82
83static void pymem_destructor(PyObject *ptr)
84{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000085 void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM);
86 if (p) {
87 PyMem_Free(p);
88 }
Benjamin Petersonb173f782009-05-05 22:31:58 +000089}
90
Thomas Heller9cac7b62008-06-06 09:31:40 +000091/*
92 ctypes maintains thread-local storage that has space for two error numbers:
93 private copies of the system 'errno' value and, on Windows, the system error code
94 accessed by the GetLastError() and SetLastError() api functions.
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000095
Thomas Heller9cac7b62008-06-06 09:31:40 +000096 Foreign functions created with CDLL(..., use_errno=True), when called, swap
97 the system 'errno' value with the private copy just before the actual
98 function call, and swapped again immediately afterwards. The 'use_errno'
99 parameter defaults to False, in this case 'ctypes_errno' is not touched.
100
101 On Windows, foreign functions created with CDLL(..., use_last_error=True) or
102 WinDLL(..., use_last_error=True) swap the system LastError value with the
103 ctypes private copy.
104
105 The values are also swapped immeditately before and after ctypes callback
106 functions are called, if the callbacks are constructed using the new
107 optional use_errno parameter set to True: CFUNCTYPE(..., use_errno=TRUE) or
108 WINFUNCTYPE(..., use_errno=True).
109
110 New ctypes functions are provided to access the ctypes private copies from
111 Python:
112
113 - ctypes.set_errno(value) and ctypes.set_last_error(value) store 'value' in
114 the private copy and returns the previous value.
115
116 - ctypes.get_errno() and ctypes.get_last_error() returns the current ctypes
117 private copies value.
118*/
119
120/*
121 This function creates and returns a thread-local Python object that has
122 space to store two integer error numbers; once created the Python object is
123 kept alive in the thread state dictionary as long as the thread itself.
124*/
125PyObject *
Thomas Heller34596a92009-04-24 20:50:00 +0000126_ctypes_get_errobj(int **pspace)
Thomas Heller9cac7b62008-06-06 09:31:40 +0000127{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000128 PyObject *dict = PyThreadState_GetDict();
129 PyObject *errobj;
130 static PyObject *error_object_name;
131 if (dict == 0) {
132 PyErr_SetString(PyExc_RuntimeError,
133 "cannot get thread state");
134 return NULL;
135 }
136 if (error_object_name == NULL) {
137 error_object_name = PyUnicode_InternFromString("ctypes.error_object");
138 if (error_object_name == NULL)
139 return NULL;
140 }
141 errobj = PyDict_GetItem(dict, error_object_name);
142 if (errobj) {
143 if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) {
144 PyErr_SetString(PyExc_RuntimeError,
145 "ctypes.error_object is an invalid capsule");
146 return NULL;
147 }
148 Py_INCREF(errobj);
149 }
150 else {
151 void *space = PyMem_Malloc(sizeof(int) * 2);
152 if (space == NULL)
153 return NULL;
154 memset(space, 0, sizeof(int) * 2);
155 errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
156 if (errobj == NULL)
157 return NULL;
158 if (-1 == PyDict_SetItem(dict, error_object_name,
159 errobj)) {
160 Py_DECREF(errobj);
161 return NULL;
162 }
163 }
164 *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM);
165 return errobj;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000166}
167
168static PyObject *
169get_error_internal(PyObject *self, PyObject *args, int index)
170{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000171 int *space;
172 PyObject *errobj = _ctypes_get_errobj(&space);
173 PyObject *result;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000174
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000175 if (errobj == NULL)
176 return NULL;
177 result = PyLong_FromLong(space[index]);
178 Py_DECREF(errobj);
179 return result;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000180}
181
182static PyObject *
183set_error_internal(PyObject *self, PyObject *args, int index)
184{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000185 int new_errno, old_errno;
186 PyObject *errobj;
187 int *space;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000188
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000189 if (!PyArg_ParseTuple(args, "i", &new_errno))
190 return NULL;
191 errobj = _ctypes_get_errobj(&space);
192 if (errobj == NULL)
193 return NULL;
194 old_errno = space[index];
195 space[index] = new_errno;
196 Py_DECREF(errobj);
197 return PyLong_FromLong(old_errno);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000198}
199
200static PyObject *
201get_errno(PyObject *self, PyObject *args)
202{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000203 return get_error_internal(self, args, 0);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000204}
205
206static PyObject *
207set_errno(PyObject *self, PyObject *args)
208{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000209 return set_error_internal(self, args, 0);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000210}
211
Thomas Hellerd4c93202006-03-08 19:35:11 +0000212#ifdef MS_WIN32
Thomas Heller9cac7b62008-06-06 09:31:40 +0000213
214static PyObject *
215get_last_error(PyObject *self, PyObject *args)
216{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000217 return get_error_internal(self, args, 1);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000218}
219
220static PyObject *
221set_last_error(PyObject *self, PyObject *args)
222{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000223 return set_error_internal(self, args, 1);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000224}
225
Thomas Hellerd4c93202006-03-08 19:35:11 +0000226PyObject *ComError;
227
Thomas Heller71fb5132008-11-26 08:45:36 +0000228static WCHAR *FormatError(DWORD code)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000229{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000230 WCHAR *lpMsgBuf;
231 DWORD n;
232 n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
233 NULL,
234 code,
235 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
236 (LPWSTR) &lpMsgBuf,
237 0,
238 NULL);
239 if (n) {
240 while (iswspace(lpMsgBuf[n-1]))
241 --n;
242 lpMsgBuf[n] = L'\0'; /* rstrip() */
243 }
244 return lpMsgBuf;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000245}
246
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000247#ifndef DONT_USE_SEH
Thomas Heller84c97af2009-04-25 16:49:23 +0000248static void SetException(DWORD code, EXCEPTION_RECORD *pr)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000249{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000250 /* The 'code' is a normal win32 error code so it could be handled by
251 PyErr_SetFromWindowsErr(). However, for some errors, we have additional
252 information not included in the error code. We handle those here and
253 delegate all others to the generic function. */
254 switch (code) {
255 case EXCEPTION_ACCESS_VIOLATION:
256 /* The thread attempted to read from or write
257 to a virtual address for which it does not
258 have the appropriate access. */
259 if (pr->ExceptionInformation[0] == 0)
260 PyErr_Format(PyExc_WindowsError,
261 "exception: access violation reading %p",
262 pr->ExceptionInformation[1]);
263 else
264 PyErr_Format(PyExc_WindowsError,
265 "exception: access violation writing %p",
266 pr->ExceptionInformation[1]);
267 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000268
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000269 case EXCEPTION_BREAKPOINT:
270 /* A breakpoint was encountered. */
271 PyErr_SetString(PyExc_WindowsError,
272 "exception: breakpoint encountered");
273 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000274
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000275 case EXCEPTION_DATATYPE_MISALIGNMENT:
276 /* The thread attempted to read or write data that is
277 misaligned on hardware that does not provide
278 alignment. For example, 16-bit values must be
279 aligned on 2-byte boundaries, 32-bit values on
280 4-byte boundaries, and so on. */
281 PyErr_SetString(PyExc_WindowsError,
282 "exception: datatype misalignment");
283 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000284
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000285 case EXCEPTION_SINGLE_STEP:
286 /* A trace trap or other single-instruction mechanism
287 signaled that one instruction has been executed. */
288 PyErr_SetString(PyExc_WindowsError,
289 "exception: single step");
290 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000291
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000292 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
293 /* The thread attempted to access an array element
294 that is out of bounds, and the underlying hardware
295 supports bounds checking. */
296 PyErr_SetString(PyExc_WindowsError,
297 "exception: array bounds exceeded");
298 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000299
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000300 case EXCEPTION_FLT_DENORMAL_OPERAND:
301 /* One of the operands in a floating-point operation
302 is denormal. A denormal value is one that is too
303 small to represent as a standard floating-point
304 value. */
305 PyErr_SetString(PyExc_WindowsError,
306 "exception: floating-point operand denormal");
307 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000308
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000309 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
310 /* The thread attempted to divide a floating-point
311 value by a floating-point divisor of zero. */
312 PyErr_SetString(PyExc_WindowsError,
313 "exception: float divide by zero");
314 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000315
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000316 case EXCEPTION_FLT_INEXACT_RESULT:
317 /* The result of a floating-point operation cannot be
318 represented exactly as a decimal fraction. */
319 PyErr_SetString(PyExc_WindowsError,
320 "exception: float inexact");
321 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000322
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000323 case EXCEPTION_FLT_INVALID_OPERATION:
324 /* This exception represents any floating-point
325 exception not included in this list. */
326 PyErr_SetString(PyExc_WindowsError,
327 "exception: float invalid operation");
328 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000329
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000330 case EXCEPTION_FLT_OVERFLOW:
331 /* The exponent of a floating-point operation is
332 greater than the magnitude allowed by the
333 corresponding type. */
334 PyErr_SetString(PyExc_WindowsError,
335 "exception: float overflow");
336 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000337
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000338 case EXCEPTION_FLT_STACK_CHECK:
339 /* The stack overflowed or underflowed as the result
340 of a floating-point operation. */
341 PyErr_SetString(PyExc_WindowsError,
342 "exception: stack over/underflow");
343 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000344
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000345 case EXCEPTION_STACK_OVERFLOW:
346 /* The stack overflowed or underflowed as the result
347 of a floating-point operation. */
348 PyErr_SetString(PyExc_WindowsError,
349 "exception: stack overflow");
350 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000351
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000352 case EXCEPTION_FLT_UNDERFLOW:
353 /* The exponent of a floating-point operation is less
354 than the magnitude allowed by the corresponding
355 type. */
356 PyErr_SetString(PyExc_WindowsError,
357 "exception: float underflow");
358 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000359
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000360 case EXCEPTION_INT_DIVIDE_BY_ZERO:
361 /* The thread attempted to divide an integer value by
362 an integer divisor of zero. */
363 PyErr_SetString(PyExc_WindowsError,
364 "exception: integer divide by zero");
365 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000366
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000367 case EXCEPTION_INT_OVERFLOW:
368 /* The result of an integer operation caused a carry
369 out of the most significant bit of the result. */
370 PyErr_SetString(PyExc_WindowsError,
371 "exception: integer overflow");
372 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000373
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000374 case EXCEPTION_PRIV_INSTRUCTION:
375 /* The thread attempted to execute an instruction
376 whose operation is not allowed in the current
377 machine mode. */
378 PyErr_SetString(PyExc_WindowsError,
379 "exception: priviledged instruction");
380 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000381
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000382 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
383 /* The thread attempted to continue execution after a
384 noncontinuable exception occurred. */
385 PyErr_SetString(PyExc_WindowsError,
386 "exception: nocontinuable");
387 break;
Thomas Heller84c97af2009-04-25 16:49:23 +0000388
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000389 default:
390 PyErr_SetFromWindowsErr(code);
391 break;
392 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000393}
394
395static DWORD HandleException(EXCEPTION_POINTERS *ptrs,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000396 DWORD *pdw, EXCEPTION_RECORD *record)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000397{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000398 *pdw = ptrs->ExceptionRecord->ExceptionCode;
399 *record = *ptrs->ExceptionRecord;
400 return EXCEPTION_EXECUTE_HANDLER;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000401}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000402#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +0000403
404static PyObject *
405check_hresult(PyObject *self, PyObject *args)
406{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000407 HRESULT hr;
408 if (!PyArg_ParseTuple(args, "i", &hr))
409 return NULL;
410 if (FAILED(hr))
411 return PyErr_SetFromWindowsErr(hr);
412 return PyLong_FromLong(hr);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000413}
414
415#endif
416
417/**************************************************************/
418
419PyCArgObject *
Thomas Heller34596a92009-04-24 20:50:00 +0000420PyCArgObject_new(void)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000421{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000422 PyCArgObject *p;
423 p = PyObject_New(PyCArgObject, &PyCArg_Type);
424 if (p == NULL)
425 return NULL;
426 p->pffi_type = NULL;
427 p->tag = '\0';
428 p->obj = NULL;
429 memset(&p->value, 0, sizeof(p->value));
430 return p;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000431}
432
433static void
434PyCArg_dealloc(PyCArgObject *self)
435{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000436 Py_XDECREF(self->obj);
437 PyObject_Del(self);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000438}
439
440static PyObject *
441PyCArg_repr(PyCArgObject *self)
442{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000443 char buffer[256];
444 switch(self->tag) {
445 case 'b':
446 case 'B':
447 sprintf(buffer, "<cparam '%c' (%d)>",
448 self->tag, self->value.b);
449 break;
450 case 'h':
451 case 'H':
452 sprintf(buffer, "<cparam '%c' (%d)>",
453 self->tag, self->value.h);
454 break;
455 case 'i':
456 case 'I':
457 sprintf(buffer, "<cparam '%c' (%d)>",
458 self->tag, self->value.i);
459 break;
460 case 'l':
461 case 'L':
462 sprintf(buffer, "<cparam '%c' (%ld)>",
463 self->tag, self->value.l);
464 break;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000465
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000466#ifdef HAVE_LONG_LONG
467 case 'q':
468 case 'Q':
469 sprintf(buffer,
470#ifdef MS_WIN32
471 "<cparam '%c' (%I64d)>",
472#else
473 "<cparam '%c' (%qd)>",
474#endif
475 self->tag, self->value.q);
476 break;
477#endif
478 case 'd':
479 sprintf(buffer, "<cparam '%c' (%f)>",
480 self->tag, self->value.d);
481 break;
482 case 'f':
483 sprintf(buffer, "<cparam '%c' (%f)>",
484 self->tag, self->value.f);
485 break;
486
487 case 'c':
488 sprintf(buffer, "<cparam '%c' (%c)>",
489 self->tag, self->value.c);
490 break;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000491
492/* Hm, are these 'z' and 'Z' codes useful at all?
493 Shouldn't they be replaced by the functionality of c_string
494 and c_wstring ?
495*/
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000496 case 'z':
497 case 'Z':
498 case 'P':
499 sprintf(buffer, "<cparam '%c' (%p)>",
500 self->tag, self->value.p);
501 break;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000502
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000503 default:
504 sprintf(buffer, "<cparam '%c' at %p>",
505 self->tag, self);
506 break;
507 }
508 return PyUnicode_FromString(buffer);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000509}
510
511static PyMemberDef PyCArgType_members[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000512 { "_obj", T_OBJECT,
513 offsetof(PyCArgObject, obj), READONLY,
514 "the wrapped object" },
515 { NULL },
Thomas Hellerd4c93202006-03-08 19:35:11 +0000516};
517
518PyTypeObject PyCArg_Type = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000519 PyVarObject_HEAD_INIT(NULL, 0)
520 "CArgObject",
521 sizeof(PyCArgObject),
522 0,
523 (destructor)PyCArg_dealloc, /* tp_dealloc */
524 0, /* tp_print */
525 0, /* tp_getattr */
526 0, /* tp_setattr */
527 0, /* tp_reserved */
528 (reprfunc)PyCArg_repr, /* tp_repr */
529 0, /* tp_as_number */
530 0, /* tp_as_sequence */
531 0, /* tp_as_mapping */
532 0, /* tp_hash */
533 0, /* tp_call */
534 0, /* tp_str */
535 0, /* tp_getattro */
536 0, /* tp_setattro */
537 0, /* tp_as_buffer */
538 Py_TPFLAGS_DEFAULT, /* tp_flags */
539 0, /* tp_doc */
540 0, /* tp_traverse */
541 0, /* tp_clear */
542 0, /* tp_richcompare */
543 0, /* tp_weaklistoffset */
544 0, /* tp_iter */
545 0, /* tp_iternext */
546 0, /* tp_methods */
547 PyCArgType_members, /* tp_members */
Thomas Hellerd4c93202006-03-08 19:35:11 +0000548};
549
550/****************************************************************/
551/*
552 * Convert a PyObject * into a parameter suitable to pass to an
553 * C function call.
554 *
555 * 1. Python integers are converted to C int and passed by value.
Thomas Heller49ac2ac2009-09-18 20:09:57 +0000556 * Py_None is converted to a C NULL pointer.
Thomas Hellerd4c93202006-03-08 19:35:11 +0000557 *
558 * 2. 3-tuples are expected to have a format character in the first
559 * item, which must be 'i', 'f', 'd', 'q', or 'P'.
560 * The second item will have to be an integer, float, double, long long
561 * or integer (denoting an address void *), will be converted to the
562 * corresponding C data type and passed by value.
563 *
564 * 3. Other Python objects are tested for an '_as_parameter_' attribute.
565 * The value of this attribute must be an integer which will be passed
566 * by value, or a 2-tuple or 3-tuple which will be used according
567 * to point 2 above. The third item (if any), is ignored. It is normally
568 * used to keep the object alive where this parameter refers to.
569 * XXX This convention is dangerous - you can construct arbitrary tuples
570 * in Python and pass them. Would it be safer to use a custom container
571 * datatype instead of a tuple?
572 *
573 * 4. Other Python objects cannot be passed as parameters - an exception is raised.
574 *
575 * 5. ConvParam will store the converted result in a struct containing format
576 * and value.
577 */
578
579union result {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000580 char c;
581 char b;
582 short h;
583 int i;
584 long l;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000585#ifdef HAVE_LONG_LONG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000586 PY_LONG_LONG q;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000587#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000588 long double D;
589 double d;
590 float f;
591 void *p;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000592};
593
594struct argument {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000595 ffi_type *ffi_type;
596 PyObject *keep;
597 union result value;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000598};
599
600/*
601 * Convert a single Python object into a PyCArgObject and return it.
602 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000603static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000604{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000605 StgDictObject *dict;
606 pa->keep = NULL; /* so we cannot forget it later */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000607
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000608 dict = PyObject_stgdict(obj);
609 if (dict) {
610 PyCArgObject *carg;
611 assert(dict->paramfunc);
612 /* If it has an stgdict, it is a CDataObject */
613 carg = dict->paramfunc((CDataObject *)obj);
614 pa->ffi_type = carg->pffi_type;
615 memcpy(&pa->value, &carg->value, sizeof(pa->value));
616 pa->keep = (PyObject *)carg;
617 return 0;
618 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000619
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000620 if (PyCArg_CheckExact(obj)) {
621 PyCArgObject *carg = (PyCArgObject *)obj;
622 pa->ffi_type = carg->pffi_type;
623 Py_INCREF(obj);
624 pa->keep = obj;
625 memcpy(&pa->value, &carg->value, sizeof(pa->value));
626 return 0;
627 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000628
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000629 /* check for None, integer, string or unicode and use directly if successful */
630 if (obj == Py_None) {
631 pa->ffi_type = &ffi_type_pointer;
632 pa->value.p = NULL;
633 return 0;
634 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000635
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000636 if (PyLong_Check(obj)) {
637 pa->ffi_type = &ffi_type_sint;
638 pa->value.i = (long)PyLong_AsUnsignedLong(obj);
639 if (pa->value.i == -1 && PyErr_Occurred()) {
640 PyErr_Clear();
641 pa->value.i = PyLong_AsLong(obj);
642 if (pa->value.i == -1 && PyErr_Occurred()) {
643 PyErr_SetString(PyExc_OverflowError,
644 "long int too long to convert");
645 return -1;
646 }
647 }
648 return 0;
649 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000650
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000651 if (PyBytes_Check(obj)) {
652 pa->ffi_type = &ffi_type_pointer;
653 pa->value.p = PyBytes_AsString(obj);
654 Py_INCREF(obj);
655 pa->keep = obj;
656 return 0;
657 }
Thomas Heller7775c712007-07-12 19:19:43 +0000658
Thomas Hellerd4c93202006-03-08 19:35:11 +0000659#ifdef CTYPES_UNICODE
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000660 if (PyUnicode_Check(obj)) {
Thomas Heller5e4e4272009-01-08 09:34:20 +0000661#ifdef HAVE_USABLE_WCHAR_T
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000662 pa->ffi_type = &ffi_type_pointer;
663 pa->value.p = PyUnicode_AS_UNICODE(obj);
664 Py_INCREF(obj);
665 pa->keep = obj;
666 return 0;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000667#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000668 int size = PyUnicode_GET_SIZE(obj);
669 pa->ffi_type = &ffi_type_pointer;
670 size += 1; /* terminating NUL */
671 size *= sizeof(wchar_t);
672 pa->value.p = PyMem_Malloc(size);
673 if (!pa->value.p) {
674 PyErr_NoMemory();
675 return -1;
676 }
677 memset(pa->value.p, 0, size);
678 pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
679 if (!pa->keep) {
680 PyMem_Free(pa->value.p);
681 return -1;
682 }
683 if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj,
684 pa->value.p, PyUnicode_GET_SIZE(obj)))
685 return -1;
686 return 0;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000687#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000688 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000689#endif
690
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000691 {
692 PyObject *arg;
693 arg = PyObject_GetAttrString(obj, "_as_parameter_");
694 /* Which types should we exactly allow here?
695 integers are required for using Python classes
696 as parameters (they have to expose the '_as_parameter_'
697 attribute)
698 */
699 if (arg) {
700 int result;
701 result = ConvParam(arg, index, pa);
702 Py_DECREF(arg);
703 return result;
704 }
705 PyErr_Format(PyExc_TypeError,
706 "Don't know how to convert parameter %d",
707 Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
708 return -1;
709 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000710}
711
712
Thomas Heller34596a92009-04-24 20:50:00 +0000713ffi_type *_ctypes_get_ffi_type(PyObject *obj)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000714{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000715 StgDictObject *dict;
716 if (obj == NULL)
717 return &ffi_type_sint;
718 dict = PyType_stgdict(obj);
719 if (dict == NULL)
720 return &ffi_type_sint;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000721#if defined(MS_WIN32) && !defined(_WIN32_WCE)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000722 /* This little trick works correctly with MSVC.
723 It returns small structures in registers
724 */
725 if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
726 if (dict->ffi_type_pointer.size <= 4)
727 return &ffi_type_sint32;
728 else if (dict->ffi_type_pointer.size <= 8)
729 return &ffi_type_sint64;
730 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000731#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000732 return &dict->ffi_type_pointer;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000733}
734
735
736/*
737 * libffi uses:
738 *
739 * ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000740 * unsigned int nargs,
Thomas Hellerd4c93202006-03-08 19:35:11 +0000741 * ffi_type *rtype,
742 * ffi_type **atypes);
743 *
744 * and then
745 *
746 * void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues);
747 */
748static int _call_function_pointer(int flags,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000749 PPROC pProc,
750 void **avalues,
751 ffi_type **atypes,
752 ffi_type *restype,
753 void *resmem,
754 int argcount)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000755{
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000756#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000757 PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000758#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000759 PyObject *error_object = NULL;
760 int *space;
761 ffi_cif cif;
762 int cc;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000763#ifdef MS_WIN32
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000764 int delta;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000765#ifndef DONT_USE_SEH
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000766 DWORD dwExceptionCode = 0;
767 EXCEPTION_RECORD record;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000768#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000769#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000770 /* XXX check before here */
771 if (restype == NULL) {
772 PyErr_SetString(PyExc_RuntimeError,
773 "No ffi_type for result");
774 return -1;
775 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000776
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000777 cc = FFI_DEFAULT_ABI;
778#if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE)
779 if ((flags & FUNCFLAG_CDECL) == 0)
780 cc = FFI_STDCALL;
781#endif
782 if (FFI_OK != ffi_prep_cif(&cif,
783 cc,
784 argcount,
785 restype,
786 atypes)) {
787 PyErr_SetString(PyExc_RuntimeError,
788 "ffi_prep_cif failed");
789 return -1;
790 }
791
792 if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
793 error_object = _ctypes_get_errobj(&space);
794 if (error_object == NULL)
795 return -1;
796 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000797#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000798 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
799 Py_UNBLOCK_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000800#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000801 if (flags & FUNCFLAG_USE_ERRNO) {
802 int temp = space[0];
803 space[0] = errno;
804 errno = temp;
805 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000806#ifdef MS_WIN32
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000807 if (flags & FUNCFLAG_USE_LASTERROR) {
808 int temp = space[1];
809 space[1] = GetLastError();
810 SetLastError(temp);
811 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000812#ifndef DONT_USE_SEH
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000813 __try {
Thomas Hellerd4c93202006-03-08 19:35:11 +0000814#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000815 delta =
Thomas Hellerd4c93202006-03-08 19:35:11 +0000816#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000817 ffi_call(&cif, (void *)pProc, resmem, avalues);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000818#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000819#ifndef DONT_USE_SEH
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000820 }
821 __except (HandleException(GetExceptionInformation(),
822 &dwExceptionCode, &record)) {
823 ;
824 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000825#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000826 if (flags & FUNCFLAG_USE_LASTERROR) {
827 int temp = space[1];
828 space[1] = GetLastError();
829 SetLastError(temp);
830 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000831#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000832 if (flags & FUNCFLAG_USE_ERRNO) {
833 int temp = space[0];
834 space[0] = errno;
835 errno = temp;
836 }
837 Py_XDECREF(error_object);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000838#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000839 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
840 Py_BLOCK_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000841#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +0000842#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000843#ifndef DONT_USE_SEH
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000844 if (dwExceptionCode) {
845 SetException(dwExceptionCode, &record);
846 return -1;
847 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848#endif
Thomas Wouters89f507f2006-12-13 04:49:30 +0000849#ifdef MS_WIN64
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000850 if (delta != 0) {
851 PyErr_Format(PyExc_RuntimeError,
852 "ffi_call failed with code %d",
853 delta);
854 return -1;
855 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000856#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000857 if (delta < 0) {
858 if (flags & FUNCFLAG_CDECL)
859 PyErr_Format(PyExc_ValueError,
860 "Procedure called with not enough "
861 "arguments (%d bytes missing) "
862 "or wrong calling convention",
863 -delta);
864 else
865 PyErr_Format(PyExc_ValueError,
866 "Procedure probably called with not enough "
867 "arguments (%d bytes missing)",
868 -delta);
869 return -1;
870 } else if (delta > 0) {
871 PyErr_Format(PyExc_ValueError,
872 "Procedure probably called with too many "
873 "arguments (%d bytes in excess)",
874 delta);
875 return -1;
876 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000877#endif
Thomas Wouters89f507f2006-12-13 04:49:30 +0000878#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000879 if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
880 return -1;
881 return 0;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000882}
883
884/*
885 * Convert the C value in result into a Python object, depending on restype.
886 *
887 * - If restype is NULL, return a Python integer.
888 * - If restype is None, return None.
889 * - If restype is a simple ctypes type (c_int, c_void_p), call the type's getfunc,
890 * pass the result to checker and return the result.
891 * - If restype is another ctypes type, return an instance of that.
892 * - Otherwise, call restype and return the result.
893 */
894static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker)
895{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000896 StgDictObject *dict;
897 PyObject *retval, *v;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000898
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000899 if (restype == NULL)
900 return PyLong_FromLong(*(int *)result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000901
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000902 if (restype == Py_None) {
903 Py_INCREF(Py_None);
904 return Py_None;
905 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000906
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000907 dict = PyType_stgdict(restype);
908 if (dict == NULL)
909 return PyObject_CallFunction(restype, "i", *(int *)result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000910
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000911 if (dict->getfunc && !_ctypes_simple_instance(restype)) {
912 retval = dict->getfunc(result, dict->size);
913 /* If restype is py_object (detected by comparing getfunc with
914 O_get), we have to call Py_DECREF because O_get has already
915 called Py_INCREF.
916 */
917 if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
918 Py_DECREF(retval);
919 }
920 } else
921 retval = PyCData_FromBaseObj(restype, NULL, 0, result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000922
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000923 if (!checker || !retval)
924 return retval;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000925
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000926 v = PyObject_CallFunctionObjArgs(checker, retval, NULL);
927 if (v == NULL)
928 _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2);
929 Py_DECREF(retval);
930 return v;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000931}
932
933/*
934 * Raise a new exception 'exc_class', adding additional text to the original
935 * exception string.
936 */
Thomas Heller34596a92009-04-24 20:50:00 +0000937void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000938{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000939 va_list vargs;
940 PyObject *tp, *v, *tb, *s, *cls_str, *msg_str;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000941
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000942 va_start(vargs, fmt);
943 s = PyUnicode_FromFormatV(fmt, vargs);
944 va_end(vargs);
945 if (!s)
946 return;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000947
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000948 PyErr_Fetch(&tp, &v, &tb);
949 PyErr_NormalizeException(&tp, &v, &tb);
950 cls_str = PyObject_Str(tp);
951 if (cls_str) {
952 PyUnicode_AppendAndDel(&s, cls_str);
953 PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": "));
954 if (s == NULL)
955 goto error;
956 } else
957 PyErr_Clear();
958 msg_str = PyObject_Str(v);
959 if (msg_str)
960 PyUnicode_AppendAndDel(&s, msg_str);
961 else {
962 PyErr_Clear();
963 PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???"));
964 if (s == NULL)
965 goto error;
966 }
967 PyErr_SetObject(exc_class, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000968error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000969 Py_XDECREF(tp);
970 Py_XDECREF(v);
971 Py_XDECREF(tb);
972 Py_XDECREF(s);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000973}
974
975
976#ifdef MS_WIN32
977
978static PyObject *
979GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk)
980{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000981 HRESULT hr;
982 ISupportErrorInfo *psei = NULL;
983 IErrorInfo *pei = NULL;
984 BSTR descr=NULL, helpfile=NULL, source=NULL;
985 GUID guid;
986 DWORD helpcontext=0;
987 LPOLESTR progid;
988 PyObject *obj;
989 LPOLESTR text;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000990
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000991 /* We absolutely have to release the GIL during COM method calls,
992 otherwise we may get a deadlock!
993 */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000994#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000995 Py_BEGIN_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000996#endif
997
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000998 hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei);
999 if (FAILED(hr))
1000 goto failed;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001001
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001002 hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid);
1003 psei->lpVtbl->Release(psei);
1004 if (FAILED(hr))
1005 goto failed;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001006
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001007 hr = GetErrorInfo(0, &pei);
1008 if (hr != S_OK)
1009 goto failed;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001010
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001011 pei->lpVtbl->GetDescription(pei, &descr);
1012 pei->lpVtbl->GetGUID(pei, &guid);
1013 pei->lpVtbl->GetHelpContext(pei, &helpcontext);
1014 pei->lpVtbl->GetHelpFile(pei, &helpfile);
1015 pei->lpVtbl->GetSource(pei, &source);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001016
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001017 pei->lpVtbl->Release(pei);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001018
Thomas Hellerd4c93202006-03-08 19:35:11 +00001019 failed:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001020#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001021 Py_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001022#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +00001023
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001024 progid = NULL;
1025 ProgIDFromCLSID(&guid, &progid);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001026
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001027 text = FormatError(errcode);
1028 obj = Py_BuildValue(
1029 "iu(uuuiu)",
1030 errcode,
1031 text,
1032 descr, source, helpfile, helpcontext,
1033 progid);
1034 if (obj) {
1035 PyErr_SetObject(ComError, obj);
1036 Py_DECREF(obj);
1037 }
1038 LocalFree(text);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001039
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001040 if (descr)
1041 SysFreeString(descr);
1042 if (helpfile)
1043 SysFreeString(helpfile);
1044 if (source)
1045 SysFreeString(source);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001046
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001047 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001048}
1049#endif
1050
1051/*
1052 * Requirements, must be ensured by the caller:
1053 * - argtuple is tuple of arguments
1054 * - argtypes is either NULL, or a tuple of the same size as argtuple
1055 *
1056 * - XXX various requirements for restype, not yet collected
1057 */
Thomas Heller34596a92009-04-24 20:50:00 +00001058PyObject *_ctypes_callproc(PPROC pProc,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001059 PyObject *argtuple,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001060#ifdef MS_WIN32
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001061 IUnknown *pIunk,
1062 GUID *iid,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001063#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001064 int flags,
1065 PyObject *argtypes, /* misleading name: This is a tuple of
1066 methods, not types: the .from_param
1067 class methods of the types */
1068 PyObject *restype,
1069 PyObject *checker)
Thomas Hellerd4c93202006-03-08 19:35:11 +00001070{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001071 Py_ssize_t i, n, argcount, argtype_count;
1072 void *resbuf;
1073 struct argument *args, *pa;
1074 ffi_type **atypes;
1075 ffi_type *rtype;
1076 void **avalues;
1077 PyObject *retval = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001078
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001079 n = argcount = PyTuple_GET_SIZE(argtuple);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001080#ifdef MS_WIN32
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001081 /* an optional COM object this pointer */
1082 if (pIunk)
1083 ++argcount;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001084#endif
1085
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001086 args = (struct argument *)alloca(sizeof(struct argument) * argcount);
1087 if (!args) {
1088 PyErr_NoMemory();
1089 return NULL;
1090 }
1091 memset(args, 0, sizeof(struct argument) * argcount);
1092 argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001093#ifdef MS_WIN32
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001094 if (pIunk) {
1095 args[0].ffi_type = &ffi_type_pointer;
1096 args[0].value.p = pIunk;
1097 pa = &args[1];
1098 } else
Thomas Hellerd4c93202006-03-08 19:35:11 +00001099#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001100 pa = &args[0];
Thomas Hellerd4c93202006-03-08 19:35:11 +00001101
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001102 /* Convert the arguments */
1103 for (i = 0; i < n; ++i, ++pa) {
1104 PyObject *converter;
1105 PyObject *arg;
1106 int err;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001107
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001108 arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */
1109 /* For cdecl functions, we allow more actual arguments
1110 than the length of the argtypes tuple.
1111 This is checked in _ctypes::PyCFuncPtr_Call
1112 */
1113 if (argtypes && argtype_count > i) {
1114 PyObject *v;
1115 converter = PyTuple_GET_ITEM(argtypes, i);
1116 v = PyObject_CallFunctionObjArgs(converter,
1117 arg,
1118 NULL);
1119 if (v == NULL) {
1120 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1121 goto cleanup;
1122 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001123
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001124 err = ConvParam(v, i+1, pa);
1125 Py_DECREF(v);
1126 if (-1 == err) {
1127 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1128 goto cleanup;
1129 }
1130 } else {
1131 err = ConvParam(arg, i+1, pa);
1132 if (-1 == err) {
1133 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1134 goto cleanup; /* leaking ? */
1135 }
1136 }
1137 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001138
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001139 rtype = _ctypes_get_ffi_type(restype);
1140 resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));
Thomas Hellerd4c93202006-03-08 19:35:11 +00001141
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001142 avalues = (void **)alloca(sizeof(void *) * argcount);
1143 atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
1144 if (!resbuf || !avalues || !atypes) {
1145 PyErr_NoMemory();
1146 goto cleanup;
1147 }
1148 for (i = 0; i < argcount; ++i) {
1149 atypes[i] = args[i].ffi_type;
1150 if (atypes[i]->type == FFI_TYPE_STRUCT
Thomas Wouters89f507f2006-12-13 04:49:30 +00001151#ifdef _WIN64
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001152 && atypes[i]->size <= sizeof(void *)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001153#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001154 )
1155 avalues[i] = (void *)args[i].value.p;
1156 else
1157 avalues[i] = (void *)&args[i].value;
1158 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001159
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001160 if (-1 == _call_function_pointer(flags, pProc, avalues, atypes,
1161 rtype, resbuf,
1162 Py_SAFE_DOWNCAST(argcount,
1163 Py_ssize_t,
1164 int)))
1165 goto cleanup;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001166
1167#ifdef WORDS_BIGENDIAN
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001168 /* libffi returns the result in a buffer with sizeof(ffi_arg). This
1169 causes problems on big endian machines, since the result buffer
1170 address cannot simply be used as result pointer, instead we must
1171 adjust the pointer value:
1172 */
1173 /*
1174 XXX I should find out and clarify why this is needed at all,
1175 especially why adjusting for ffi_type_float must be avoided on
1176 64-bit platforms.
1177 */
1178 if (rtype->type != FFI_TYPE_FLOAT
1179 && rtype->type != FFI_TYPE_STRUCT
1180 && rtype->size < sizeof(ffi_arg))
1181 resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001182#endif
1183
1184#ifdef MS_WIN32
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001185 if (iid && pIunk) {
1186 if (*(int *)resbuf & 0x80000000)
1187 retval = GetComError(*(HRESULT *)resbuf, iid, pIunk);
1188 else
1189 retval = PyLong_FromLong(*(int *)resbuf);
1190 } else if (flags & FUNCFLAG_HRESULT) {
1191 if (*(int *)resbuf & 0x80000000)
1192 retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
1193 else
1194 retval = PyLong_FromLong(*(int *)resbuf);
1195 } else
Thomas Hellerd4c93202006-03-08 19:35:11 +00001196#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001197 retval = GetResult(restype, resbuf, checker);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001198 cleanup:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001199 for (i = 0; i < argcount; ++i)
1200 Py_XDECREF(args[i].keep);
1201 return retval;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001202}
1203
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001204static int
1205_parse_voidp(PyObject *obj, void **address)
1206{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001207 *address = PyLong_AsVoidPtr(obj);
1208 if (*address == NULL)
1209 return 0;
1210 return 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001211}
1212
Thomas Hellerd4c93202006-03-08 19:35:11 +00001213#ifdef MS_WIN32
1214
Thomas Hellerd4c93202006-03-08 19:35:11 +00001215static char format_error_doc[] =
1216"FormatError([integer]) -> string\n\
1217\n\
1218Convert a win32 error code into a string. If the error code is not\n\
1219given, the return value of a call to GetLastError() is used.\n";
1220static PyObject *format_error(PyObject *self, PyObject *args)
1221{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001222 PyObject *result;
1223 wchar_t *lpMsgBuf;
1224 DWORD code = 0;
1225 if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
1226 return NULL;
1227 if (code == 0)
1228 code = GetLastError();
1229 lpMsgBuf = FormatError(code);
1230 if (lpMsgBuf) {
1231 result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf));
1232 LocalFree(lpMsgBuf);
1233 } else {
1234 result = PyUnicode_FromString("<no description>");
1235 }
1236 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001237}
1238
1239static char load_library_doc[] =
1240"LoadLibrary(name) -> handle\n\
1241\n\
1242Load an executable (usually a DLL), and return a handle to it.\n\
1243The handle may be used to locate exported functions in this\n\
1244module.\n";
1245static PyObject *load_library(PyObject *self, PyObject *args)
1246{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001247 WCHAR *name;
1248 PyObject *nameobj;
1249 PyObject *ignored;
1250 HMODULE hMod;
1251 if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
1252 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001253
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001254 name = PyUnicode_AsUnicode(nameobj);
1255 if (!name)
1256 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001257
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001258 hMod = LoadLibraryW(name);
1259 if (!hMod)
1260 return PyErr_SetFromWindowsErr(GetLastError());
Thomas Wouters89f507f2006-12-13 04:49:30 +00001261#ifdef _WIN64
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001262 return PyLong_FromVoidPtr(hMod);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001263#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001264 return Py_BuildValue("i", hMod);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001265#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +00001266}
1267
1268static char free_library_doc[] =
1269"FreeLibrary(handle) -> void\n\
1270\n\
1271Free the handle of an executable previously loaded by LoadLibrary.\n";
1272static PyObject *free_library(PyObject *self, PyObject *args)
1273{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001274 void *hMod;
1275 if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
1276 return NULL;
1277 if (!FreeLibrary((HMODULE)hMod))
1278 return PyErr_SetFromWindowsErr(GetLastError());
1279 Py_INCREF(Py_None);
1280 return Py_None;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001281}
1282
1283/* obsolete, should be removed */
1284/* Only used by sample code (in samples\Windows\COM.py) */
1285static PyObject *
1286call_commethod(PyObject *self, PyObject *args)
1287{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001288 IUnknown *pIunk;
1289 int index;
1290 PyObject *arguments;
1291 PPROC *lpVtbl;
1292 PyObject *result;
1293 CDataObject *pcom;
1294 PyObject *argtypes = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001295
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001296 if (!PyArg_ParseTuple(args,
1297 "OiO!|O!",
1298 &pcom, &index,
1299 &PyTuple_Type, &arguments,
1300 &PyTuple_Type, &argtypes))
1301 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001302
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001303 if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) {
1304 PyErr_Format(PyExc_TypeError,
1305 "Method takes %d arguments (%d given)",
1306 PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments));
1307 return NULL;
1308 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001309
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001310 if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) {
1311 PyErr_Format(PyExc_TypeError,
1312 "COM Pointer expected instead of %s instance",
1313 Py_TYPE(pcom)->tp_name);
1314 return NULL;
1315 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001316
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001317 if ((*(void **)(pcom->b_ptr)) == NULL) {
1318 PyErr_SetString(PyExc_ValueError,
1319 "The COM 'this' pointer is NULL");
1320 return NULL;
1321 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001322
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001323 pIunk = (IUnknown *)(*(void **)(pcom->b_ptr));
1324 lpVtbl = (PPROC *)(pIunk->lpVtbl);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001325
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001326 result = _ctypes_callproc(lpVtbl[index],
1327 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001328#ifdef MS_WIN32
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001329 pIunk,
1330 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001331#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001332 FUNCFLAG_HRESULT, /* flags */
1333 argtypes, /* self->argtypes */
1334 NULL, /* self->restype */
1335 NULL); /* checker */
1336 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001337}
1338
1339static char copy_com_pointer_doc[] =
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001340"CopyComPointer(src, dst) -> HRESULT value\n";
Thomas Hellerd4c93202006-03-08 19:35:11 +00001341
1342static PyObject *
1343copy_com_pointer(PyObject *self, PyObject *args)
1344{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001345 PyObject *p1, *p2, *r = NULL;
1346 struct argument a, b;
1347 IUnknown *src, **pdst;
1348 if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
1349 return NULL;
1350 a.keep = b.keep = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001351
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001352 if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b))
1353 goto done;
1354 src = (IUnknown *)a.value.p;
1355 pdst = (IUnknown **)b.value.p;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001356
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001357 if (pdst == NULL)
1358 r = PyLong_FromLong(E_POINTER);
1359 else {
1360 if (src)
1361 src->lpVtbl->AddRef(src);
1362 *pdst = src;
1363 r = PyLong_FromLong(S_OK);
1364 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001365 done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001366 Py_XDECREF(a.keep);
1367 Py_XDECREF(b.keep);
1368 return r;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001369}
1370#else
1371
1372static PyObject *py_dl_open(PyObject *self, PyObject *args)
1373{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001374 PyObject *name, *name2;
1375 char *name_str;
1376 void * handle;
1377#ifdef RTLD_LOCAL
1378 int mode = RTLD_NOW | RTLD_LOCAL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001379#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001380 /* cygwin doesn't define RTLD_LOCAL */
1381 int mode = RTLD_NOW;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001382#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001383 if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode))
1384 return NULL;
1385 mode |= RTLD_NOW;
1386 if (name != Py_None) {
1387 if (PyUnicode_FSConverter(name, &name2) == 0)
1388 return NULL;
1389 if (PyBytes_Check(name2))
1390 name_str = PyBytes_AS_STRING(name2);
1391 else
1392 name_str = PyByteArray_AS_STRING(name2);
1393 } else {
1394 name_str = NULL;
1395 name2 = NULL;
1396 }
1397 handle = ctypes_dlopen(name_str, mode);
1398 Py_XDECREF(name2);
1399 if (!handle) {
1400 char *errmsg = ctypes_dlerror();
1401 if (!errmsg)
1402 errmsg = "dlopen() error";
1403 PyErr_SetString(PyExc_OSError,
1404 errmsg);
1405 return NULL;
1406 }
1407 return PyLong_FromVoidPtr(handle);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001408}
1409
1410static PyObject *py_dl_close(PyObject *self, PyObject *args)
1411{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001412 void *handle;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001413
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001414 if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
1415 return NULL;
1416 if (dlclose(handle)) {
1417 PyErr_SetString(PyExc_OSError,
1418 ctypes_dlerror());
1419 return NULL;
1420 }
1421 Py_INCREF(Py_None);
1422 return Py_None;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001423}
1424
1425static PyObject *py_dl_sym(PyObject *self, PyObject *args)
1426{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001427 char *name;
1428 void *handle;
1429 void *ptr;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001430
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001431 if (!PyArg_ParseTuple(args, "O&s:dlsym",
1432 &_parse_voidp, &handle, &name))
1433 return NULL;
1434 ptr = ctypes_dlsym((void*)handle, name);
1435 if (!ptr) {
1436 PyErr_SetString(PyExc_OSError,
1437 ctypes_dlerror());
1438 return NULL;
1439 }
1440 return PyLong_FromVoidPtr(ptr);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001441}
1442#endif
1443
1444/*
1445 * Only for debugging so far: So that we can call CFunction instances
1446 *
1447 * XXX Needs to accept more arguments: flags, argtypes, restype
1448 */
1449static PyObject *
1450call_function(PyObject *self, PyObject *args)
1451{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001452 void *func;
1453 PyObject *arguments;
1454 PyObject *result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001455
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001456 if (!PyArg_ParseTuple(args,
1457 "O&O!",
1458 &_parse_voidp, &func,
1459 &PyTuple_Type, &arguments))
1460 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001461
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001462 result = _ctypes_callproc((PPROC)func,
1463 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001464#ifdef MS_WIN32
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001465 NULL,
1466 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001467#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001468 0, /* flags */
1469 NULL, /* self->argtypes */
1470 NULL, /* self->restype */
1471 NULL); /* checker */
1472 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001473}
1474
1475/*
1476 * Only for debugging so far: So that we can call CFunction instances
1477 *
1478 * XXX Needs to accept more arguments: flags, argtypes, restype
1479 */
1480static PyObject *
1481call_cdeclfunction(PyObject *self, PyObject *args)
1482{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001483 void *func;
1484 PyObject *arguments;
1485 PyObject *result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001486
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001487 if (!PyArg_ParseTuple(args,
1488 "O&O!",
1489 &_parse_voidp, &func,
1490 &PyTuple_Type, &arguments))
1491 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001492
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001493 result = _ctypes_callproc((PPROC)func,
1494 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001495#ifdef MS_WIN32
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001496 NULL,
1497 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001498#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001499 FUNCFLAG_CDECL, /* flags */
1500 NULL, /* self->argtypes */
1501 NULL, /* self->restype */
1502 NULL); /* checker */
1503 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001504}
1505
1506/*****************************************************************
1507 * functions
1508 */
1509static char sizeof_doc[] =
1510"sizeof(C type) -> integer\n"
1511"sizeof(C instance) -> integer\n"
1512"Return the size in bytes of a C instance";
1513
1514static PyObject *
1515sizeof_func(PyObject *self, PyObject *obj)
1516{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001517 StgDictObject *dict;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001518
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001519 dict = PyType_stgdict(obj);
1520 if (dict)
1521 return PyLong_FromSsize_t(dict->size);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001522
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001523 if (CDataObject_Check(obj))
1524 return PyLong_FromSsize_t(((CDataObject *)obj)->b_size);
1525 PyErr_SetString(PyExc_TypeError,
1526 "this type has no size");
1527 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001528}
1529
1530static char alignment_doc[] =
1531"alignment(C type) -> integer\n"
1532"alignment(C instance) -> integer\n"
1533"Return the alignment requirements of a C instance";
1534
1535static PyObject *
1536align_func(PyObject *self, PyObject *obj)
1537{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001538 StgDictObject *dict;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001539
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001540 dict = PyType_stgdict(obj);
1541 if (dict)
1542 return PyLong_FromSsize_t(dict->align);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001543
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001544 dict = PyObject_stgdict(obj);
1545 if (dict)
1546 return PyLong_FromSsize_t(dict->align);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001547
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001548 PyErr_SetString(PyExc_TypeError,
1549 "no alignment info");
1550 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001551}
1552
1553static char byref_doc[] =
Thomas Hellerc5d01262008-06-10 15:08:51 +00001554"byref(C instance[, offset=0]) -> byref-object\n"
Thomas Hellerd4c93202006-03-08 19:35:11 +00001555"Return a pointer lookalike to a C instance, only usable\n"
1556"as function argument";
1557
1558/*
1559 * We must return something which can be converted to a parameter,
1560 * but still has a reference to self.
1561 */
1562static PyObject *
Thomas Hellerc5d01262008-06-10 15:08:51 +00001563byref(PyObject *self, PyObject *args)
Thomas Hellerd4c93202006-03-08 19:35:11 +00001564{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001565 PyCArgObject *parg;
1566 PyObject *obj;
1567 PyObject *pyoffset = NULL;
1568 Py_ssize_t offset = 0;
Thomas Hellerc5d01262008-06-10 15:08:51 +00001569
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001570 if (!PyArg_UnpackTuple(args, "byref", 1, 2,
1571 &obj, &pyoffset))
1572 return NULL;
1573 if (pyoffset) {
1574 offset = PyNumber_AsSsize_t(pyoffset, NULL);
1575 if (offset == -1 && PyErr_Occurred())
1576 return NULL;
1577 }
1578 if (!CDataObject_Check(obj)) {
1579 PyErr_Format(PyExc_TypeError,
1580 "byref() argument must be a ctypes instance, not '%s'",
1581 Py_TYPE(obj)->tp_name);
1582 return NULL;
1583 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001584
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001585 parg = PyCArgObject_new();
1586 if (parg == NULL)
1587 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001588
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001589 parg->tag = 'P';
1590 parg->pffi_type = &ffi_type_pointer;
1591 Py_INCREF(obj);
1592 parg->obj = obj;
1593 parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
1594 return (PyObject *)parg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001595}
1596
1597static char addressof_doc[] =
1598"addressof(C instance) -> integer\n"
1599"Return the address of the C instance internal buffer";
1600
1601static PyObject *
1602addressof(PyObject *self, PyObject *obj)
1603{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001604 if (CDataObject_Check(obj))
1605 return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
1606 PyErr_SetString(PyExc_TypeError,
1607 "invalid type");
1608 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001609}
1610
1611static int
1612converter(PyObject *obj, void **address)
1613{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001614 *address = PyLong_AsVoidPtr(obj);
1615 return *address != NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001616}
1617
1618static PyObject *
1619My_PyObj_FromPtr(PyObject *self, PyObject *args)
1620{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001621 PyObject *ob;
1622 if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob))
1623 return NULL;
1624 Py_INCREF(ob);
1625 return ob;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001626}
1627
1628static PyObject *
1629My_Py_INCREF(PyObject *self, PyObject *arg)
1630{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001631 Py_INCREF(arg); /* that's what this function is for */
1632 Py_INCREF(arg); /* that for returning it */
1633 return arg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001634}
1635
1636static PyObject *
1637My_Py_DECREF(PyObject *self, PyObject *arg)
1638{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001639 Py_DECREF(arg); /* that's what this function is for */
1640 Py_INCREF(arg); /* that's for returning it */
1641 return arg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001642}
1643
1644#ifdef CTYPES_UNICODE
1645
1646static char set_conversion_mode_doc[] =
1647"set_conversion_mode(encoding, errors) -> (previous-encoding, previous-errors)\n\
1648\n\
1649Set the encoding and error handling ctypes uses when converting\n\
1650between unicode and strings. Returns the previous values.\n";
1651
1652static PyObject *
1653set_conversion_mode(PyObject *self, PyObject *args)
1654{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001655 char *coding, *mode;
1656 PyObject *result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001657
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001658 if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode))
1659 return NULL;
1660 result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors);
1661 if (coding) {
1662 PyMem_Free(_ctypes_conversion_encoding);
1663 _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1);
1664 strcpy(_ctypes_conversion_encoding, coding);
1665 } else {
1666 _ctypes_conversion_encoding = NULL;
1667 }
1668 PyMem_Free(_ctypes_conversion_errors);
1669 _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1);
1670 strcpy(_ctypes_conversion_errors, mode);
1671 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001672}
1673#endif
1674
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001675static PyObject *
1676resize(PyObject *self, PyObject *args)
1677{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001678 CDataObject *obj;
1679 StgDictObject *dict;
1680 Py_ssize_t size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001681
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001682 if (!PyArg_ParseTuple(args,
1683 "On:resize",
1684 &obj, &size))
1685 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001686
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001687 dict = PyObject_stgdict((PyObject *)obj);
1688 if (dict == NULL) {
1689 PyErr_SetString(PyExc_TypeError,
1690 "excepted ctypes instance");
1691 return NULL;
1692 }
1693 if (size < dict->size) {
1694 PyErr_Format(PyExc_ValueError,
1695 "minimum size is %zd",
1696 dict->size);
1697 return NULL;
1698 }
1699 if (obj->b_needsfree == 0) {
1700 PyErr_Format(PyExc_ValueError,
1701 "Memory cannot be resized because this object doesn't own it");
1702 return NULL;
1703 }
1704 if (size <= sizeof(obj->b_value)) {
1705 /* internal default buffer is large enough */
1706 obj->b_size = size;
1707 goto done;
1708 }
1709 if (obj->b_size <= sizeof(obj->b_value)) {
1710 /* We are currently using the objects default buffer, but it
1711 isn't large enough any more. */
1712 void *ptr = PyMem_Malloc(size);
1713 if (ptr == NULL)
1714 return PyErr_NoMemory();
1715 memset(ptr, 0, size);
1716 memmove(ptr, obj->b_ptr, obj->b_size);
1717 obj->b_ptr = ptr;
1718 obj->b_size = size;
1719 } else {
1720 void * ptr = PyMem_Realloc(obj->b_ptr, size);
1721 if (ptr == NULL)
1722 return PyErr_NoMemory();
1723 obj->b_ptr = ptr;
1724 obj->b_size = size;
1725 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001726 done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001727 Py_INCREF(Py_None);
1728 return Py_None;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001729}
1730
Thomas Heller13394e92008-02-13 20:40:44 +00001731static PyObject *
1732unpickle(PyObject *self, PyObject *args)
1733{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001734 PyObject *typ;
1735 PyObject *state;
1736 PyObject *result;
1737 PyObject *tmp;
Thomas Heller13394e92008-02-13 20:40:44 +00001738
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001739 if (!PyArg_ParseTuple(args, "OO", &typ, &state))
1740 return NULL;
1741 result = PyObject_CallMethod(typ, "__new__", "O", typ);
1742 if (result == NULL)
1743 return NULL;
1744 tmp = PyObject_CallMethod(result, "__setstate__", "O", state);
1745 if (tmp == NULL) {
1746 Py_DECREF(result);
1747 return NULL;
1748 }
1749 Py_DECREF(tmp);
1750 return result;
Thomas Heller13394e92008-02-13 20:40:44 +00001751}
1752
Thomas Heller3071f812008-04-14 16:17:33 +00001753static PyObject *
1754POINTER(PyObject *self, PyObject *cls)
1755{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001756 PyObject *result;
1757 PyTypeObject *typ;
1758 PyObject *key;
1759 char *buf;
Thomas Heller3071f812008-04-14 16:17:33 +00001760
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001761 result = PyDict_GetItem(_ctypes_ptrtype_cache, cls);
1762 if (result) {
1763 Py_INCREF(result);
1764 return result;
1765 }
1766 if (PyUnicode_CheckExact(cls)) {
1767 char *name = _PyUnicode_AsString(cls);
1768 buf = alloca(strlen(name) + 3 + 1);
1769 sprintf(buf, "LP_%s", name);
1770 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
1771 "s(O){}",
1772 buf,
1773 &PyCPointer_Type);
1774 if (result == NULL)
1775 return result;
1776 key = PyLong_FromVoidPtr(result);
1777 } else if (PyType_Check(cls)) {
1778 typ = (PyTypeObject *)cls;
1779 buf = alloca(strlen(typ->tp_name) + 3 + 1);
1780 sprintf(buf, "LP_%s", typ->tp_name);
1781 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
1782 "s(O){sO}",
1783 buf,
1784 &PyCPointer_Type,
1785 "_type_", cls);
1786 if (result == NULL)
1787 return result;
1788 Py_INCREF(cls);
1789 key = cls;
1790 } else {
1791 PyErr_SetString(PyExc_TypeError, "must be a ctypes type");
1792 return NULL;
1793 }
1794 if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) {
1795 Py_DECREF(result);
1796 Py_DECREF(key);
1797 return NULL;
1798 }
1799 Py_DECREF(key);
1800 return result;
Thomas Heller3071f812008-04-14 16:17:33 +00001801}
1802
1803static PyObject *
1804pointer(PyObject *self, PyObject *arg)
1805{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001806 PyObject *result;
1807 PyObject *typ;
Thomas Heller3071f812008-04-14 16:17:33 +00001808
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001809 typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg));
1810 if (typ)
1811 return PyObject_CallFunctionObjArgs(typ, arg, NULL);
1812 typ = POINTER(NULL, (PyObject *)Py_TYPE(arg));
1813 if (typ == NULL)
1814 return NULL;
1815 result = PyObject_CallFunctionObjArgs(typ, arg, NULL);
1816 Py_DECREF(typ);
1817 return result;
Thomas Heller3071f812008-04-14 16:17:33 +00001818}
1819
Thomas Hellerb041fda2008-04-30 17:11:46 +00001820static PyObject *
1821buffer_info(PyObject *self, PyObject *arg)
1822{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001823 StgDictObject *dict = PyType_stgdict(arg);
1824 PyObject *shape;
1825 Py_ssize_t i;
Thomas Hellerb041fda2008-04-30 17:11:46 +00001826
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001827 if (dict == NULL)
1828 dict = PyObject_stgdict(arg);
1829 if (dict == NULL) {
1830 PyErr_SetString(PyExc_TypeError,
1831 "not a ctypes type or object");
1832 return NULL;
1833 }
1834 shape = PyTuple_New(dict->ndim);
1835 if (shape == NULL)
1836 return NULL;
1837 for (i = 0; i < (int)dict->ndim; ++i)
1838 PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i]));
Thomas Hellerb041fda2008-04-30 17:11:46 +00001839
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001840 if (PyErr_Occurred()) {
1841 Py_DECREF(shape);
1842 return NULL;
1843 }
1844 return Py_BuildValue("siN", dict->format, dict->ndim, shape);
Thomas Hellerb041fda2008-04-30 17:11:46 +00001845}
1846
Thomas Heller34596a92009-04-24 20:50:00 +00001847PyMethodDef _ctypes_module_methods[] = {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001848 {"get_errno", get_errno, METH_NOARGS},
1849 {"set_errno", set_errno, METH_VARARGS},
1850 {"POINTER", POINTER, METH_O },
1851 {"pointer", pointer, METH_O },
1852 {"_unpickle", unpickle, METH_VARARGS },
1853 {"buffer_info", buffer_info, METH_O, "Return buffer interface information"},
1854 {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001855#ifdef CTYPES_UNICODE
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001856 {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001857#endif
1858#ifdef MS_WIN32
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001859 {"get_last_error", get_last_error, METH_NOARGS},
1860 {"set_last_error", set_last_error, METH_VARARGS},
1861 {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
1862 {"FormatError", format_error, METH_VARARGS, format_error_doc},
1863 {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
1864 {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
1865 {"call_commethod", call_commethod, METH_VARARGS },
1866 {"_check_HRESULT", check_hresult, METH_VARARGS},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001867#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001868 {"dlopen", py_dl_open, METH_VARARGS,
1869 "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
1870 {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
1871 {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001872#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001873 {"alignment", align_func, METH_O, alignment_doc},
1874 {"sizeof", sizeof_func, METH_O, sizeof_doc},
1875 {"byref", byref, METH_VARARGS, byref_doc},
1876 {"addressof", addressof, METH_O, addressof_doc},
1877 {"call_function", call_function, METH_VARARGS },
1878 {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
1879 {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
1880 {"Py_INCREF", My_Py_INCREF, METH_O },
1881 {"Py_DECREF", My_Py_DECREF, METH_O },
1882 {NULL, NULL} /* Sentinel */
Thomas Hellerd4c93202006-03-08 19:35:11 +00001883};
1884
1885/*
1886 Local Variables:
1887 compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"
1888 End:
1889*/