blob: 0d4578c5de0c9fc9d4172a79944c0850c66928c2 [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 Pitrouf95a1b32010-05-09 15:52:27 +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
Terry Jan Reedy0158af32013-03-11 17:42:46 -040023 'inargs', or a completely fresh tuple, depending on several things (is it a
24 COM method?, are 'paramflags' available?).
Thomas Hellerd4c93202006-03-08 19:35:11 +000025
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
Ezio Melotti13925002011-03-16 11:05:33 +020032 second array has 'void *' entries.
Thomas Hellerd4c93202006-03-08 19:35:11 +000033
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)
Ezio Melotti42da6632011-03-15 05:18:48 +020052 - the 'struct arguments' array
Thomas Hellerd4c93202006-03-08 19:35:11 +000053 - 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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000171 int *space;
172 PyObject *errobj = _ctypes_get_errobj(&space);
173 PyObject *result;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000185 int new_errno, old_errno;
186 PyObject *errobj;
187 int *space;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000396 DWORD *pdw, EXCEPTION_RECORD *record)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Heller69b639f2009-09-18 20:08:39 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000586 PY_LONG_LONG q;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000587#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000605 StgDictObject *dict;
606 pa->keep = NULL; /* so we cannot forget it later */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000660 if (PyUnicode_Check(obj)) {
Daniel Stutzbach8515eae2010-08-24 21:57:33 +0000661#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000668 pa->ffi_type = &ffi_type_pointer;
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000669 pa->value.p = PyUnicode_AsWideCharString(obj, NULL);
Victor Stinner4c2e4fa2010-09-29 10:37:16 +0000670 if (pa->value.p == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
673 if (!pa->keep) {
674 PyMem_Free(pa->value.p);
675 return -1;
676 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 return 0;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000678#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000680#endif
681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 {
683 PyObject *arg;
684 arg = PyObject_GetAttrString(obj, "_as_parameter_");
685 /* Which types should we exactly allow here?
686 integers are required for using Python classes
687 as parameters (they have to expose the '_as_parameter_'
688 attribute)
689 */
690 if (arg) {
691 int result;
692 result = ConvParam(arg, index, pa);
693 Py_DECREF(arg);
694 return result;
695 }
696 PyErr_Format(PyExc_TypeError,
697 "Don't know how to convert parameter %d",
698 Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
699 return -1;
700 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000701}
702
703
Thomas Heller34596a92009-04-24 20:50:00 +0000704ffi_type *_ctypes_get_ffi_type(PyObject *obj)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 StgDictObject *dict;
707 if (obj == NULL)
708 return &ffi_type_sint;
709 dict = PyType_stgdict(obj);
710 if (dict == NULL)
711 return &ffi_type_sint;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000712#if defined(MS_WIN32) && !defined(_WIN32_WCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 /* This little trick works correctly with MSVC.
714 It returns small structures in registers
715 */
716 if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
717 if (dict->ffi_type_pointer.size <= 4)
718 return &ffi_type_sint32;
719 else if (dict->ffi_type_pointer.size <= 8)
720 return &ffi_type_sint64;
721 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000722#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 return &dict->ffi_type_pointer;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000724}
725
726
727/*
728 * libffi uses:
729 *
730 * ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 * unsigned int nargs,
Thomas Hellerd4c93202006-03-08 19:35:11 +0000732 * ffi_type *rtype,
733 * ffi_type **atypes);
734 *
735 * and then
736 *
737 * void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues);
738 */
739static int _call_function_pointer(int flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 PPROC pProc,
741 void **avalues,
742 ffi_type **atypes,
743 ffi_type *restype,
744 void *resmem,
745 int argcount)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000746{
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000747#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000749#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 PyObject *error_object = NULL;
751 int *space;
752 ffi_cif cif;
753 int cc;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000754#ifdef MS_WIN32
Thomas Hellerb00697e2010-06-21 16:00:31 +0000755 int delta;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000756#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 DWORD dwExceptionCode = 0;
758 EXCEPTION_RECORD record;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000759#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000760#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 /* XXX check before here */
762 if (restype == NULL) {
763 PyErr_SetString(PyExc_RuntimeError,
764 "No ffi_type for result");
765 return -1;
766 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 cc = FFI_DEFAULT_ABI;
769#if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE)
770 if ((flags & FUNCFLAG_CDECL) == 0)
771 cc = FFI_STDCALL;
772#endif
773 if (FFI_OK != ffi_prep_cif(&cif,
774 cc,
775 argcount,
776 restype,
777 atypes)) {
778 PyErr_SetString(PyExc_RuntimeError,
779 "ffi_prep_cif failed");
780 return -1;
781 }
782
783 if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
784 error_object = _ctypes_get_errobj(&space);
785 if (error_object == NULL)
786 return -1;
787 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000788#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
790 Py_UNBLOCK_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000791#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 if (flags & FUNCFLAG_USE_ERRNO) {
793 int temp = space[0];
794 space[0] = errno;
795 errno = temp;
796 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000797#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 if (flags & FUNCFLAG_USE_LASTERROR) {
799 int temp = space[1];
800 space[1] = GetLastError();
801 SetLastError(temp);
802 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000803#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 __try {
Thomas Hellerd4c93202006-03-08 19:35:11 +0000805#endif
Thomas Hellerb00697e2010-06-21 16:00:31 +0000806 delta =
Thomas Hellerd4c93202006-03-08 19:35:11 +0000807#endif
Thomas Hellerb00697e2010-06-21 16:00:31 +0000808 ffi_call(&cif, (void *)pProc, resmem, avalues);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000809#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000810#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 }
812 __except (HandleException(GetExceptionInformation(),
813 &dwExceptionCode, &record)) {
814 ;
815 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000816#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (flags & FUNCFLAG_USE_LASTERROR) {
818 int temp = space[1];
819 space[1] = GetLastError();
820 SetLastError(temp);
821 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000822#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (flags & FUNCFLAG_USE_ERRNO) {
824 int temp = space[0];
825 space[0] = errno;
826 errno = temp;
827 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000828#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
830 Py_BLOCK_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000831#endif
Kristjan Valur Jonsson9946bd62012-12-21 09:41:25 +0000832 Py_XDECREF(error_object);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000833#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000834#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (dwExceptionCode) {
836 SetException(dwExceptionCode, &record);
837 return -1;
838 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000839#endif
Thomas Hellerb00697e2010-06-21 16:00:31 +0000840#ifdef MS_WIN64
841 if (delta != 0) {
842 PyErr_Format(PyExc_RuntimeError,
843 "ffi_call failed with code %d",
844 delta);
845 return -1;
846 }
847#else
848 if (delta < 0) {
849 if (flags & FUNCFLAG_CDECL)
850 PyErr_Format(PyExc_ValueError,
851 "Procedure called with not enough "
852 "arguments (%d bytes missing) "
853 "or wrong calling convention",
854 -delta);
855 else
856 PyErr_Format(PyExc_ValueError,
857 "Procedure probably called with not enough "
858 "arguments (%d bytes missing)",
859 -delta);
860 return -1;
861 } else if (delta > 0) {
862 PyErr_Format(PyExc_ValueError,
863 "Procedure probably called with too many "
864 "arguments (%d bytes in excess)",
865 delta);
866 return -1;
867 }
868#endif
Thomas Wouters89f507f2006-12-13 04:49:30 +0000869#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
871 return -1;
872 return 0;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000873}
874
875/*
876 * Convert the C value in result into a Python object, depending on restype.
877 *
878 * - If restype is NULL, return a Python integer.
879 * - If restype is None, return None.
880 * - If restype is a simple ctypes type (c_int, c_void_p), call the type's getfunc,
881 * pass the result to checker and return the result.
882 * - If restype is another ctypes type, return an instance of that.
883 * - Otherwise, call restype and return the result.
884 */
885static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker)
886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 StgDictObject *dict;
888 PyObject *retval, *v;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 if (restype == NULL)
891 return PyLong_FromLong(*(int *)result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 if (restype == Py_None) {
894 Py_INCREF(Py_None);
895 return Py_None;
896 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 dict = PyType_stgdict(restype);
899 if (dict == NULL)
900 return PyObject_CallFunction(restype, "i", *(int *)result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 if (dict->getfunc && !_ctypes_simple_instance(restype)) {
903 retval = dict->getfunc(result, dict->size);
904 /* If restype is py_object (detected by comparing getfunc with
905 O_get), we have to call Py_DECREF because O_get has already
906 called Py_INCREF.
907 */
908 if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
909 Py_DECREF(retval);
910 }
911 } else
912 retval = PyCData_FromBaseObj(restype, NULL, 0, result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 if (!checker || !retval)
915 return retval;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 v = PyObject_CallFunctionObjArgs(checker, retval, NULL);
918 if (v == NULL)
919 _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2);
920 Py_DECREF(retval);
921 return v;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000922}
923
924/*
925 * Raise a new exception 'exc_class', adding additional text to the original
926 * exception string.
927 */
Thomas Heller34596a92009-04-24 20:50:00 +0000928void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 va_list vargs;
931 PyObject *tp, *v, *tb, *s, *cls_str, *msg_str;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 va_start(vargs, fmt);
934 s = PyUnicode_FromFormatV(fmt, vargs);
935 va_end(vargs);
936 if (!s)
937 return;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 PyErr_Fetch(&tp, &v, &tb);
940 PyErr_NormalizeException(&tp, &v, &tb);
941 cls_str = PyObject_Str(tp);
942 if (cls_str) {
943 PyUnicode_AppendAndDel(&s, cls_str);
944 PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": "));
945 if (s == NULL)
946 goto error;
947 } else
948 PyErr_Clear();
949 msg_str = PyObject_Str(v);
950 if (msg_str)
951 PyUnicode_AppendAndDel(&s, msg_str);
952 else {
953 PyErr_Clear();
954 PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???"));
955 if (s == NULL)
956 goto error;
957 }
958 PyErr_SetObject(exc_class, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000959error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 Py_XDECREF(tp);
961 Py_XDECREF(v);
962 Py_XDECREF(tb);
963 Py_XDECREF(s);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000964}
965
966
967#ifdef MS_WIN32
968
969static PyObject *
970GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk)
971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 HRESULT hr;
973 ISupportErrorInfo *psei = NULL;
974 IErrorInfo *pei = NULL;
975 BSTR descr=NULL, helpfile=NULL, source=NULL;
976 GUID guid;
977 DWORD helpcontext=0;
978 LPOLESTR progid;
979 PyObject *obj;
980 LPOLESTR text;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 /* We absolutely have to release the GIL during COM method calls,
983 otherwise we may get a deadlock!
984 */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000985#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 Py_BEGIN_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000987#endif
988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei);
990 if (FAILED(hr))
991 goto failed;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid);
994 psei->lpVtbl->Release(psei);
995 if (FAILED(hr))
996 goto failed;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 hr = GetErrorInfo(0, &pei);
999 if (hr != S_OK)
1000 goto failed;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 pei->lpVtbl->GetDescription(pei, &descr);
1003 pei->lpVtbl->GetGUID(pei, &guid);
1004 pei->lpVtbl->GetHelpContext(pei, &helpcontext);
1005 pei->lpVtbl->GetHelpFile(pei, &helpfile);
1006 pei->lpVtbl->GetSource(pei, &source);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 pei->lpVtbl->Release(pei);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001009
Thomas Hellerd4c93202006-03-08 19:35:11 +00001010 failed:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001011#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 Py_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001013#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 progid = NULL;
1016 ProgIDFromCLSID(&guid, &progid);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 text = FormatError(errcode);
1019 obj = Py_BuildValue(
1020 "iu(uuuiu)",
1021 errcode,
1022 text,
1023 descr, source, helpfile, helpcontext,
1024 progid);
1025 if (obj) {
1026 PyErr_SetObject(ComError, obj);
1027 Py_DECREF(obj);
1028 }
1029 LocalFree(text);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (descr)
1032 SysFreeString(descr);
1033 if (helpfile)
1034 SysFreeString(helpfile);
1035 if (source)
1036 SysFreeString(source);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001039}
1040#endif
1041
1042/*
1043 * Requirements, must be ensured by the caller:
1044 * - argtuple is tuple of arguments
1045 * - argtypes is either NULL, or a tuple of the same size as argtuple
1046 *
1047 * - XXX various requirements for restype, not yet collected
1048 */
Thomas Heller34596a92009-04-24 20:50:00 +00001049PyObject *_ctypes_callproc(PPROC pProc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 PyObject *argtuple,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001051#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 IUnknown *pIunk,
1053 GUID *iid,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001054#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 int flags,
1056 PyObject *argtypes, /* misleading name: This is a tuple of
1057 methods, not types: the .from_param
1058 class methods of the types */
1059 PyObject *restype,
1060 PyObject *checker)
Thomas Hellerd4c93202006-03-08 19:35:11 +00001061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 Py_ssize_t i, n, argcount, argtype_count;
1063 void *resbuf;
1064 struct argument *args, *pa;
1065 ffi_type **atypes;
1066 ffi_type *rtype;
1067 void **avalues;
1068 PyObject *retval = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 n = argcount = PyTuple_GET_SIZE(argtuple);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001071#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 /* an optional COM object this pointer */
1073 if (pIunk)
1074 ++argcount;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001075#endif
1076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 args = (struct argument *)alloca(sizeof(struct argument) * argcount);
1078 if (!args) {
1079 PyErr_NoMemory();
1080 return NULL;
1081 }
1082 memset(args, 0, sizeof(struct argument) * argcount);
1083 argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001084#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 if (pIunk) {
1086 args[0].ffi_type = &ffi_type_pointer;
1087 args[0].value.p = pIunk;
1088 pa = &args[1];
1089 } else
Thomas Hellerd4c93202006-03-08 19:35:11 +00001090#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 pa = &args[0];
Thomas Hellerd4c93202006-03-08 19:35:11 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 /* Convert the arguments */
1094 for (i = 0; i < n; ++i, ++pa) {
1095 PyObject *converter;
1096 PyObject *arg;
1097 int err;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */
1100 /* For cdecl functions, we allow more actual arguments
1101 than the length of the argtypes tuple.
1102 This is checked in _ctypes::PyCFuncPtr_Call
1103 */
1104 if (argtypes && argtype_count > i) {
1105 PyObject *v;
1106 converter = PyTuple_GET_ITEM(argtypes, i);
1107 v = PyObject_CallFunctionObjArgs(converter,
1108 arg,
1109 NULL);
1110 if (v == NULL) {
1111 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1112 goto cleanup;
1113 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 err = ConvParam(v, i+1, pa);
1116 Py_DECREF(v);
1117 if (-1 == err) {
1118 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1119 goto cleanup;
1120 }
1121 } else {
1122 err = ConvParam(arg, i+1, pa);
1123 if (-1 == err) {
1124 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1125 goto cleanup; /* leaking ? */
1126 }
1127 }
1128 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 rtype = _ctypes_get_ffi_type(restype);
1131 resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));
Thomas Hellerd4c93202006-03-08 19:35:11 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 avalues = (void **)alloca(sizeof(void *) * argcount);
1134 atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
1135 if (!resbuf || !avalues || !atypes) {
1136 PyErr_NoMemory();
1137 goto cleanup;
1138 }
1139 for (i = 0; i < argcount; ++i) {
1140 atypes[i] = args[i].ffi_type;
Victor Stinner4c2e4fa2010-09-29 10:37:16 +00001141 if (atypes[i]->type == FFI_TYPE_STRUCT
Thomas Hellerb00697e2010-06-21 16:00:31 +00001142#ifdef _WIN64
1143 && atypes[i]->size <= sizeof(void *)
1144#endif
1145 )
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 avalues[i] = (void *)args[i].value.p;
1147 else
1148 avalues[i] = (void *)&args[i].value;
1149 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 if (-1 == _call_function_pointer(flags, pProc, avalues, atypes,
1152 rtype, resbuf,
1153 Py_SAFE_DOWNCAST(argcount,
1154 Py_ssize_t,
1155 int)))
1156 goto cleanup;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001157
1158#ifdef WORDS_BIGENDIAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 /* libffi returns the result in a buffer with sizeof(ffi_arg). This
1160 causes problems on big endian machines, since the result buffer
1161 address cannot simply be used as result pointer, instead we must
1162 adjust the pointer value:
1163 */
1164 /*
1165 XXX I should find out and clarify why this is needed at all,
1166 especially why adjusting for ffi_type_float must be avoided on
1167 64-bit platforms.
1168 */
1169 if (rtype->type != FFI_TYPE_FLOAT
1170 && rtype->type != FFI_TYPE_STRUCT
1171 && rtype->size < sizeof(ffi_arg))
1172 resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001173#endif
1174
1175#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 if (iid && pIunk) {
1177 if (*(int *)resbuf & 0x80000000)
1178 retval = GetComError(*(HRESULT *)resbuf, iid, pIunk);
1179 else
1180 retval = PyLong_FromLong(*(int *)resbuf);
1181 } else if (flags & FUNCFLAG_HRESULT) {
1182 if (*(int *)resbuf & 0x80000000)
1183 retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
1184 else
1185 retval = PyLong_FromLong(*(int *)resbuf);
1186 } else
Thomas Hellerd4c93202006-03-08 19:35:11 +00001187#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 retval = GetResult(restype, resbuf, checker);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001189 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 for (i = 0; i < argcount; ++i)
1191 Py_XDECREF(args[i].keep);
1192 return retval;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001193}
1194
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001195static int
1196_parse_voidp(PyObject *obj, void **address)
1197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 *address = PyLong_AsVoidPtr(obj);
1199 if (*address == NULL)
1200 return 0;
1201 return 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001202}
1203
Thomas Hellerd4c93202006-03-08 19:35:11 +00001204#ifdef MS_WIN32
1205
Thomas Hellerd4c93202006-03-08 19:35:11 +00001206static char format_error_doc[] =
1207"FormatError([integer]) -> string\n\
1208\n\
1209Convert a win32 error code into a string. If the error code is not\n\
1210given, the return value of a call to GetLastError() is used.\n";
1211static PyObject *format_error(PyObject *self, PyObject *args)
1212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 PyObject *result;
1214 wchar_t *lpMsgBuf;
1215 DWORD code = 0;
1216 if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
1217 return NULL;
1218 if (code == 0)
1219 code = GetLastError();
1220 lpMsgBuf = FormatError(code);
1221 if (lpMsgBuf) {
1222 result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf));
1223 LocalFree(lpMsgBuf);
1224 } else {
1225 result = PyUnicode_FromString("<no description>");
1226 }
1227 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001228}
1229
1230static char load_library_doc[] =
1231"LoadLibrary(name) -> handle\n\
1232\n\
1233Load an executable (usually a DLL), and return a handle to it.\n\
1234The handle may be used to locate exported functions in this\n\
1235module.\n";
1236static PyObject *load_library(PyObject *self, PyObject *args)
1237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 WCHAR *name;
1239 PyObject *nameobj;
1240 PyObject *ignored;
1241 HMODULE hMod;
1242 if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
1243 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 name = PyUnicode_AsUnicode(nameobj);
1246 if (!name)
1247 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 hMod = LoadLibraryW(name);
1250 if (!hMod)
1251 return PyErr_SetFromWindowsErr(GetLastError());
Thomas Wouters89f507f2006-12-13 04:49:30 +00001252#ifdef _WIN64
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 return PyLong_FromVoidPtr(hMod);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001254#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 return Py_BuildValue("i", hMod);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001256#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +00001257}
1258
1259static char free_library_doc[] =
1260"FreeLibrary(handle) -> void\n\
1261\n\
1262Free the handle of an executable previously loaded by LoadLibrary.\n";
1263static PyObject *free_library(PyObject *self, PyObject *args)
1264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 void *hMod;
1266 if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
1267 return NULL;
1268 if (!FreeLibrary((HMODULE)hMod))
1269 return PyErr_SetFromWindowsErr(GetLastError());
1270 Py_INCREF(Py_None);
1271 return Py_None;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001272}
1273
1274/* obsolete, should be removed */
1275/* Only used by sample code (in samples\Windows\COM.py) */
1276static PyObject *
1277call_commethod(PyObject *self, PyObject *args)
1278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 IUnknown *pIunk;
1280 int index;
1281 PyObject *arguments;
1282 PPROC *lpVtbl;
1283 PyObject *result;
1284 CDataObject *pcom;
1285 PyObject *argtypes = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (!PyArg_ParseTuple(args,
1288 "OiO!|O!",
1289 &pcom, &index,
1290 &PyTuple_Type, &arguments,
1291 &PyTuple_Type, &argtypes))
1292 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) {
1295 PyErr_Format(PyExc_TypeError,
1296 "Method takes %d arguments (%d given)",
1297 PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments));
1298 return NULL;
1299 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) {
1302 PyErr_Format(PyExc_TypeError,
1303 "COM Pointer expected instead of %s instance",
1304 Py_TYPE(pcom)->tp_name);
1305 return NULL;
1306 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 if ((*(void **)(pcom->b_ptr)) == NULL) {
1309 PyErr_SetString(PyExc_ValueError,
1310 "The COM 'this' pointer is NULL");
1311 return NULL;
1312 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 pIunk = (IUnknown *)(*(void **)(pcom->b_ptr));
1315 lpVtbl = (PPROC *)(pIunk->lpVtbl);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 result = _ctypes_callproc(lpVtbl[index],
1318 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001319#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 pIunk,
1321 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001322#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 FUNCFLAG_HRESULT, /* flags */
1324 argtypes, /* self->argtypes */
1325 NULL, /* self->restype */
1326 NULL); /* checker */
1327 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001328}
1329
1330static char copy_com_pointer_doc[] =
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001331"CopyComPointer(src, dst) -> HRESULT value\n";
Thomas Hellerd4c93202006-03-08 19:35:11 +00001332
1333static PyObject *
1334copy_com_pointer(PyObject *self, PyObject *args)
1335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 PyObject *p1, *p2, *r = NULL;
1337 struct argument a, b;
1338 IUnknown *src, **pdst;
1339 if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
1340 return NULL;
1341 a.keep = b.keep = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b))
1344 goto done;
1345 src = (IUnknown *)a.value.p;
1346 pdst = (IUnknown **)b.value.p;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 if (pdst == NULL)
1349 r = PyLong_FromLong(E_POINTER);
1350 else {
1351 if (src)
1352 src->lpVtbl->AddRef(src);
1353 *pdst = src;
1354 r = PyLong_FromLong(S_OK);
1355 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001356 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 Py_XDECREF(a.keep);
1358 Py_XDECREF(b.keep);
1359 return r;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001360}
1361#else
1362
1363static PyObject *py_dl_open(PyObject *self, PyObject *args)
1364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 PyObject *name, *name2;
1366 char *name_str;
1367 void * handle;
1368#ifdef RTLD_LOCAL
1369 int mode = RTLD_NOW | RTLD_LOCAL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001370#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 /* cygwin doesn't define RTLD_LOCAL */
1372 int mode = RTLD_NOW;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001373#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode))
1375 return NULL;
1376 mode |= RTLD_NOW;
1377 if (name != Py_None) {
1378 if (PyUnicode_FSConverter(name, &name2) == 0)
1379 return NULL;
1380 if (PyBytes_Check(name2))
1381 name_str = PyBytes_AS_STRING(name2);
1382 else
1383 name_str = PyByteArray_AS_STRING(name2);
1384 } else {
1385 name_str = NULL;
1386 name2 = NULL;
1387 }
1388 handle = ctypes_dlopen(name_str, mode);
1389 Py_XDECREF(name2);
1390 if (!handle) {
1391 char *errmsg = ctypes_dlerror();
1392 if (!errmsg)
1393 errmsg = "dlopen() error";
1394 PyErr_SetString(PyExc_OSError,
1395 errmsg);
1396 return NULL;
1397 }
1398 return PyLong_FromVoidPtr(handle);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001399}
1400
1401static PyObject *py_dl_close(PyObject *self, PyObject *args)
1402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 void *handle;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
1406 return NULL;
1407 if (dlclose(handle)) {
1408 PyErr_SetString(PyExc_OSError,
1409 ctypes_dlerror());
1410 return NULL;
1411 }
1412 Py_INCREF(Py_None);
1413 return Py_None;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001414}
1415
1416static PyObject *py_dl_sym(PyObject *self, PyObject *args)
1417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 char *name;
1419 void *handle;
1420 void *ptr;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 if (!PyArg_ParseTuple(args, "O&s:dlsym",
1423 &_parse_voidp, &handle, &name))
1424 return NULL;
1425 ptr = ctypes_dlsym((void*)handle, name);
1426 if (!ptr) {
1427 PyErr_SetString(PyExc_OSError,
1428 ctypes_dlerror());
1429 return NULL;
1430 }
1431 return PyLong_FromVoidPtr(ptr);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001432}
1433#endif
1434
1435/*
1436 * Only for debugging so far: So that we can call CFunction instances
1437 *
1438 * XXX Needs to accept more arguments: flags, argtypes, restype
1439 */
1440static PyObject *
1441call_function(PyObject *self, PyObject *args)
1442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 void *func;
1444 PyObject *arguments;
1445 PyObject *result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (!PyArg_ParseTuple(args,
1448 "O&O!",
1449 &_parse_voidp, &func,
1450 &PyTuple_Type, &arguments))
1451 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 result = _ctypes_callproc((PPROC)func,
1454 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001455#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 NULL,
1457 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001458#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 0, /* flags */
1460 NULL, /* self->argtypes */
1461 NULL, /* self->restype */
1462 NULL); /* checker */
1463 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001464}
1465
1466/*
1467 * Only for debugging so far: So that we can call CFunction instances
1468 *
1469 * XXX Needs to accept more arguments: flags, argtypes, restype
1470 */
1471static PyObject *
1472call_cdeclfunction(PyObject *self, PyObject *args)
1473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 void *func;
1475 PyObject *arguments;
1476 PyObject *result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 if (!PyArg_ParseTuple(args,
1479 "O&O!",
1480 &_parse_voidp, &func,
1481 &PyTuple_Type, &arguments))
1482 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 result = _ctypes_callproc((PPROC)func,
1485 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001486#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 NULL,
1488 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001489#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 FUNCFLAG_CDECL, /* flags */
1491 NULL, /* self->argtypes */
1492 NULL, /* self->restype */
1493 NULL); /* checker */
1494 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001495}
1496
1497/*****************************************************************
1498 * functions
1499 */
1500static char sizeof_doc[] =
1501"sizeof(C type) -> integer\n"
1502"sizeof(C instance) -> integer\n"
1503"Return the size in bytes of a C instance";
1504
1505static PyObject *
1506sizeof_func(PyObject *self, PyObject *obj)
1507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 StgDictObject *dict;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 dict = PyType_stgdict(obj);
1511 if (dict)
1512 return PyLong_FromSsize_t(dict->size);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 if (CDataObject_Check(obj))
1515 return PyLong_FromSsize_t(((CDataObject *)obj)->b_size);
1516 PyErr_SetString(PyExc_TypeError,
1517 "this type has no size");
1518 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001519}
1520
1521static char alignment_doc[] =
1522"alignment(C type) -> integer\n"
1523"alignment(C instance) -> integer\n"
1524"Return the alignment requirements of a C instance";
1525
1526static PyObject *
1527align_func(PyObject *self, PyObject *obj)
1528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 StgDictObject *dict;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 dict = PyType_stgdict(obj);
1532 if (dict)
1533 return PyLong_FromSsize_t(dict->align);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 dict = PyObject_stgdict(obj);
1536 if (dict)
1537 return PyLong_FromSsize_t(dict->align);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 PyErr_SetString(PyExc_TypeError,
1540 "no alignment info");
1541 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001542}
1543
1544static char byref_doc[] =
Thomas Hellerc5d01262008-06-10 15:08:51 +00001545"byref(C instance[, offset=0]) -> byref-object\n"
Thomas Hellerd4c93202006-03-08 19:35:11 +00001546"Return a pointer lookalike to a C instance, only usable\n"
1547"as function argument";
1548
1549/*
1550 * We must return something which can be converted to a parameter,
1551 * but still has a reference to self.
1552 */
1553static PyObject *
Thomas Hellerc5d01262008-06-10 15:08:51 +00001554byref(PyObject *self, PyObject *args)
Thomas Hellerd4c93202006-03-08 19:35:11 +00001555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 PyCArgObject *parg;
1557 PyObject *obj;
1558 PyObject *pyoffset = NULL;
1559 Py_ssize_t offset = 0;
Thomas Hellerc5d01262008-06-10 15:08:51 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 if (!PyArg_UnpackTuple(args, "byref", 1, 2,
1562 &obj, &pyoffset))
1563 return NULL;
1564 if (pyoffset) {
1565 offset = PyNumber_AsSsize_t(pyoffset, NULL);
1566 if (offset == -1 && PyErr_Occurred())
1567 return NULL;
1568 }
1569 if (!CDataObject_Check(obj)) {
1570 PyErr_Format(PyExc_TypeError,
1571 "byref() argument must be a ctypes instance, not '%s'",
1572 Py_TYPE(obj)->tp_name);
1573 return NULL;
1574 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 parg = PyCArgObject_new();
1577 if (parg == NULL)
1578 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 parg->tag = 'P';
1581 parg->pffi_type = &ffi_type_pointer;
1582 Py_INCREF(obj);
1583 parg->obj = obj;
1584 parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
1585 return (PyObject *)parg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001586}
1587
1588static char addressof_doc[] =
1589"addressof(C instance) -> integer\n"
1590"Return the address of the C instance internal buffer";
1591
1592static PyObject *
1593addressof(PyObject *self, PyObject *obj)
1594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 if (CDataObject_Check(obj))
1596 return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
1597 PyErr_SetString(PyExc_TypeError,
1598 "invalid type");
1599 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001600}
1601
1602static int
1603converter(PyObject *obj, void **address)
1604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 *address = PyLong_AsVoidPtr(obj);
1606 return *address != NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001607}
1608
1609static PyObject *
1610My_PyObj_FromPtr(PyObject *self, PyObject *args)
1611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 PyObject *ob;
1613 if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob))
1614 return NULL;
1615 Py_INCREF(ob);
1616 return ob;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001617}
1618
1619static PyObject *
1620My_Py_INCREF(PyObject *self, PyObject *arg)
1621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 Py_INCREF(arg); /* that's what this function is for */
1623 Py_INCREF(arg); /* that for returning it */
1624 return arg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001625}
1626
1627static PyObject *
1628My_Py_DECREF(PyObject *self, PyObject *arg)
1629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 Py_DECREF(arg); /* that's what this function is for */
1631 Py_INCREF(arg); /* that's for returning it */
1632 return arg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001633}
1634
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001635static PyObject *
1636resize(PyObject *self, PyObject *args)
1637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 CDataObject *obj;
1639 StgDictObject *dict;
1640 Py_ssize_t size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 if (!PyArg_ParseTuple(args,
1643 "On:resize",
1644 &obj, &size))
1645 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 dict = PyObject_stgdict((PyObject *)obj);
1648 if (dict == NULL) {
1649 PyErr_SetString(PyExc_TypeError,
1650 "excepted ctypes instance");
1651 return NULL;
1652 }
1653 if (size < dict->size) {
1654 PyErr_Format(PyExc_ValueError,
1655 "minimum size is %zd",
1656 dict->size);
1657 return NULL;
1658 }
1659 if (obj->b_needsfree == 0) {
1660 PyErr_Format(PyExc_ValueError,
1661 "Memory cannot be resized because this object doesn't own it");
1662 return NULL;
1663 }
1664 if (size <= sizeof(obj->b_value)) {
1665 /* internal default buffer is large enough */
1666 obj->b_size = size;
1667 goto done;
1668 }
Antoine Pitrou305e1a72012-12-08 11:05:50 +01001669 if (!_CDataObject_HasExternalBuffer(obj)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 /* We are currently using the objects default buffer, but it
1671 isn't large enough any more. */
1672 void *ptr = PyMem_Malloc(size);
1673 if (ptr == NULL)
1674 return PyErr_NoMemory();
1675 memset(ptr, 0, size);
1676 memmove(ptr, obj->b_ptr, obj->b_size);
1677 obj->b_ptr = ptr;
1678 obj->b_size = size;
1679 } else {
1680 void * ptr = PyMem_Realloc(obj->b_ptr, size);
1681 if (ptr == NULL)
1682 return PyErr_NoMemory();
1683 obj->b_ptr = ptr;
1684 obj->b_size = size;
1685 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001686 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 Py_INCREF(Py_None);
1688 return Py_None;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001689}
1690
Thomas Heller13394e92008-02-13 20:40:44 +00001691static PyObject *
1692unpickle(PyObject *self, PyObject *args)
1693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 PyObject *typ;
1695 PyObject *state;
1696 PyObject *result;
1697 PyObject *tmp;
Thomas Heller13394e92008-02-13 20:40:44 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 if (!PyArg_ParseTuple(args, "OO", &typ, &state))
1700 return NULL;
1701 result = PyObject_CallMethod(typ, "__new__", "O", typ);
1702 if (result == NULL)
1703 return NULL;
1704 tmp = PyObject_CallMethod(result, "__setstate__", "O", state);
1705 if (tmp == NULL) {
1706 Py_DECREF(result);
1707 return NULL;
1708 }
1709 Py_DECREF(tmp);
1710 return result;
Thomas Heller13394e92008-02-13 20:40:44 +00001711}
1712
Thomas Heller3071f812008-04-14 16:17:33 +00001713static PyObject *
1714POINTER(PyObject *self, PyObject *cls)
1715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 PyObject *result;
1717 PyTypeObject *typ;
1718 PyObject *key;
1719 char *buf;
Thomas Heller3071f812008-04-14 16:17:33 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 result = PyDict_GetItem(_ctypes_ptrtype_cache, cls);
1722 if (result) {
1723 Py_INCREF(result);
1724 return result;
1725 }
1726 if (PyUnicode_CheckExact(cls)) {
1727 char *name = _PyUnicode_AsString(cls);
1728 buf = alloca(strlen(name) + 3 + 1);
1729 sprintf(buf, "LP_%s", name);
1730 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
1731 "s(O){}",
1732 buf,
1733 &PyCPointer_Type);
1734 if (result == NULL)
1735 return result;
1736 key = PyLong_FromVoidPtr(result);
1737 } else if (PyType_Check(cls)) {
1738 typ = (PyTypeObject *)cls;
1739 buf = alloca(strlen(typ->tp_name) + 3 + 1);
1740 sprintf(buf, "LP_%s", typ->tp_name);
1741 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
1742 "s(O){sO}",
1743 buf,
1744 &PyCPointer_Type,
1745 "_type_", cls);
1746 if (result == NULL)
1747 return result;
1748 Py_INCREF(cls);
1749 key = cls;
1750 } else {
1751 PyErr_SetString(PyExc_TypeError, "must be a ctypes type");
1752 return NULL;
1753 }
1754 if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) {
1755 Py_DECREF(result);
1756 Py_DECREF(key);
1757 return NULL;
1758 }
1759 Py_DECREF(key);
1760 return result;
Thomas Heller3071f812008-04-14 16:17:33 +00001761}
1762
1763static PyObject *
1764pointer(PyObject *self, PyObject *arg)
1765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 PyObject *result;
1767 PyObject *typ;
Thomas Heller3071f812008-04-14 16:17:33 +00001768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg));
1770 if (typ)
1771 return PyObject_CallFunctionObjArgs(typ, arg, NULL);
1772 typ = POINTER(NULL, (PyObject *)Py_TYPE(arg));
1773 if (typ == NULL)
1774 return NULL;
1775 result = PyObject_CallFunctionObjArgs(typ, arg, NULL);
1776 Py_DECREF(typ);
1777 return result;
Thomas Heller3071f812008-04-14 16:17:33 +00001778}
1779
Thomas Hellerb041fda2008-04-30 17:11:46 +00001780static PyObject *
1781buffer_info(PyObject *self, PyObject *arg)
1782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 StgDictObject *dict = PyType_stgdict(arg);
1784 PyObject *shape;
1785 Py_ssize_t i;
Thomas Hellerb041fda2008-04-30 17:11:46 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 if (dict == NULL)
1788 dict = PyObject_stgdict(arg);
1789 if (dict == NULL) {
1790 PyErr_SetString(PyExc_TypeError,
1791 "not a ctypes type or object");
1792 return NULL;
1793 }
1794 shape = PyTuple_New(dict->ndim);
1795 if (shape == NULL)
1796 return NULL;
1797 for (i = 0; i < (int)dict->ndim; ++i)
1798 PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i]));
Thomas Hellerb041fda2008-04-30 17:11:46 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 if (PyErr_Occurred()) {
1801 Py_DECREF(shape);
1802 return NULL;
1803 }
1804 return Py_BuildValue("siN", dict->format, dict->ndim, shape);
Thomas Hellerb041fda2008-04-30 17:11:46 +00001805}
1806
Thomas Heller34596a92009-04-24 20:50:00 +00001807PyMethodDef _ctypes_module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 {"get_errno", get_errno, METH_NOARGS},
1809 {"set_errno", set_errno, METH_VARARGS},
1810 {"POINTER", POINTER, METH_O },
1811 {"pointer", pointer, METH_O },
1812 {"_unpickle", unpickle, METH_VARARGS },
1813 {"buffer_info", buffer_info, METH_O, "Return buffer interface information"},
1814 {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001815#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 {"get_last_error", get_last_error, METH_NOARGS},
1817 {"set_last_error", set_last_error, METH_VARARGS},
1818 {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
1819 {"FormatError", format_error, METH_VARARGS, format_error_doc},
1820 {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
1821 {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
1822 {"call_commethod", call_commethod, METH_VARARGS },
1823 {"_check_HRESULT", check_hresult, METH_VARARGS},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001824#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 {"dlopen", py_dl_open, METH_VARARGS,
1826 "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
1827 {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
1828 {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001829#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 {"alignment", align_func, METH_O, alignment_doc},
1831 {"sizeof", sizeof_func, METH_O, sizeof_doc},
1832 {"byref", byref, METH_VARARGS, byref_doc},
1833 {"addressof", addressof, METH_O, addressof_doc},
1834 {"call_function", call_function, METH_VARARGS },
1835 {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
1836 {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
1837 {"Py_INCREF", My_Py_INCREF, METH_O },
1838 {"Py_DECREF", My_Py_DECREF, METH_O },
1839 {NULL, NULL} /* Sentinel */
Thomas Hellerd4c93202006-03-08 19:35:11 +00001840};
1841
1842/*
1843 Local Variables:
1844 compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"
1845 End:
1846*/