blob: dd441f5b165608377e8f75caae2422da81d1e0f8 [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
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
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)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 pa->ffi_type = &ffi_type_pointer;
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000662 pa->value.p = PyUnicode_AsWideCharString(obj, NULL);
Victor Stinner4c2e4fa2010-09-29 10:37:16 +0000663 if (pa->value.p == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
666 if (!pa->keep) {
667 PyMem_Free(pa->value.p);
668 return -1;
669 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000672#endif
673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 {
675 PyObject *arg;
676 arg = PyObject_GetAttrString(obj, "_as_parameter_");
677 /* Which types should we exactly allow here?
678 integers are required for using Python classes
679 as parameters (they have to expose the '_as_parameter_'
680 attribute)
681 */
682 if (arg) {
683 int result;
684 result = ConvParam(arg, index, pa);
685 Py_DECREF(arg);
686 return result;
687 }
688 PyErr_Format(PyExc_TypeError,
689 "Don't know how to convert parameter %d",
690 Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
691 return -1;
692 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000693}
694
695
Thomas Heller34596a92009-04-24 20:50:00 +0000696ffi_type *_ctypes_get_ffi_type(PyObject *obj)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 StgDictObject *dict;
699 if (obj == NULL)
700 return &ffi_type_sint;
701 dict = PyType_stgdict(obj);
702 if (dict == NULL)
703 return &ffi_type_sint;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000704#if defined(MS_WIN32) && !defined(_WIN32_WCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 /* This little trick works correctly with MSVC.
706 It returns small structures in registers
707 */
708 if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
709 if (dict->ffi_type_pointer.size <= 4)
710 return &ffi_type_sint32;
711 else if (dict->ffi_type_pointer.size <= 8)
712 return &ffi_type_sint64;
713 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000714#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 return &dict->ffi_type_pointer;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000716}
717
718
719/*
720 * libffi uses:
721 *
722 * ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 * unsigned int nargs,
Thomas Hellerd4c93202006-03-08 19:35:11 +0000724 * ffi_type *rtype,
725 * ffi_type **atypes);
726 *
727 * and then
728 *
729 * void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues);
730 */
731static int _call_function_pointer(int flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PPROC pProc,
733 void **avalues,
734 ffi_type **atypes,
735 ffi_type *restype,
736 void *resmem,
737 int argcount)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000738{
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000739#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000741#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 PyObject *error_object = NULL;
743 int *space;
744 ffi_cif cif;
745 int cc;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000746#ifdef MS_WIN32
Thomas Hellerb00697e2010-06-21 16:00:31 +0000747 int delta;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000748#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 DWORD dwExceptionCode = 0;
750 EXCEPTION_RECORD record;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000751#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000752#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 /* XXX check before here */
754 if (restype == NULL) {
755 PyErr_SetString(PyExc_RuntimeError,
756 "No ffi_type for result");
757 return -1;
758 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 cc = FFI_DEFAULT_ABI;
761#if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE)
762 if ((flags & FUNCFLAG_CDECL) == 0)
763 cc = FFI_STDCALL;
764#endif
765 if (FFI_OK != ffi_prep_cif(&cif,
766 cc,
767 argcount,
768 restype,
769 atypes)) {
770 PyErr_SetString(PyExc_RuntimeError,
771 "ffi_prep_cif failed");
772 return -1;
773 }
774
775 if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
776 error_object = _ctypes_get_errobj(&space);
777 if (error_object == NULL)
778 return -1;
779 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000780#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
782 Py_UNBLOCK_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000783#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (flags & FUNCFLAG_USE_ERRNO) {
785 int temp = space[0];
786 space[0] = errno;
787 errno = temp;
788 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000789#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (flags & FUNCFLAG_USE_LASTERROR) {
791 int temp = space[1];
792 space[1] = GetLastError();
793 SetLastError(temp);
794 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000795#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 __try {
Thomas Hellerd4c93202006-03-08 19:35:11 +0000797#endif
Thomas Hellerb00697e2010-06-21 16:00:31 +0000798 delta =
Thomas Hellerd4c93202006-03-08 19:35:11 +0000799#endif
Thomas Hellerb00697e2010-06-21 16:00:31 +0000800 ffi_call(&cif, (void *)pProc, resmem, avalues);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000801#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000802#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 }
804 __except (HandleException(GetExceptionInformation(),
805 &dwExceptionCode, &record)) {
806 ;
807 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000808#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 if (flags & FUNCFLAG_USE_LASTERROR) {
810 int temp = space[1];
811 space[1] = GetLastError();
812 SetLastError(temp);
813 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000814#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 if (flags & FUNCFLAG_USE_ERRNO) {
816 int temp = space[0];
817 space[0] = errno;
818 errno = temp;
819 }
820 Py_XDECREF(error_object);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000821#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
823 Py_BLOCK_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000824#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +0000825#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826#ifndef DONT_USE_SEH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 if (dwExceptionCode) {
828 SetException(dwExceptionCode, &record);
829 return -1;
830 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000831#endif
Thomas Hellerb00697e2010-06-21 16:00:31 +0000832#ifdef MS_WIN64
833 if (delta != 0) {
834 PyErr_Format(PyExc_RuntimeError,
835 "ffi_call failed with code %d",
836 delta);
837 return -1;
838 }
839#else
840 if (delta < 0) {
841 if (flags & FUNCFLAG_CDECL)
842 PyErr_Format(PyExc_ValueError,
843 "Procedure called with not enough "
844 "arguments (%d bytes missing) "
845 "or wrong calling convention",
846 -delta);
847 else
848 PyErr_Format(PyExc_ValueError,
849 "Procedure probably called with not enough "
850 "arguments (%d bytes missing)",
851 -delta);
852 return -1;
853 } else if (delta > 0) {
854 PyErr_Format(PyExc_ValueError,
855 "Procedure probably called with too many "
856 "arguments (%d bytes in excess)",
857 delta);
858 return -1;
859 }
860#endif
Thomas Wouters89f507f2006-12-13 04:49:30 +0000861#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
863 return -1;
864 return 0;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000865}
866
867/*
868 * Convert the C value in result into a Python object, depending on restype.
869 *
870 * - If restype is NULL, return a Python integer.
871 * - If restype is None, return None.
872 * - If restype is a simple ctypes type (c_int, c_void_p), call the type's getfunc,
873 * pass the result to checker and return the result.
874 * - If restype is another ctypes type, return an instance of that.
875 * - Otherwise, call restype and return the result.
876 */
877static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker)
878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 StgDictObject *dict;
880 PyObject *retval, *v;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 if (restype == NULL)
883 return PyLong_FromLong(*(int *)result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 if (restype == Py_None) {
886 Py_INCREF(Py_None);
887 return Py_None;
888 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 dict = PyType_stgdict(restype);
891 if (dict == NULL)
892 return PyObject_CallFunction(restype, "i", *(int *)result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 if (dict->getfunc && !_ctypes_simple_instance(restype)) {
895 retval = dict->getfunc(result, dict->size);
896 /* If restype is py_object (detected by comparing getfunc with
897 O_get), we have to call Py_DECREF because O_get has already
898 called Py_INCREF.
899 */
900 if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
901 Py_DECREF(retval);
902 }
903 } else
904 retval = PyCData_FromBaseObj(restype, NULL, 0, result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 if (!checker || !retval)
907 return retval;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 v = PyObject_CallFunctionObjArgs(checker, retval, NULL);
910 if (v == NULL)
911 _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2);
912 Py_DECREF(retval);
913 return v;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000914}
915
916/*
917 * Raise a new exception 'exc_class', adding additional text to the original
918 * exception string.
919 */
Thomas Heller34596a92009-04-24 20:50:00 +0000920void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 va_list vargs;
923 PyObject *tp, *v, *tb, *s, *cls_str, *msg_str;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 va_start(vargs, fmt);
926 s = PyUnicode_FromFormatV(fmt, vargs);
927 va_end(vargs);
928 if (!s)
929 return;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 PyErr_Fetch(&tp, &v, &tb);
932 PyErr_NormalizeException(&tp, &v, &tb);
933 cls_str = PyObject_Str(tp);
934 if (cls_str) {
935 PyUnicode_AppendAndDel(&s, cls_str);
936 PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": "));
937 if (s == NULL)
938 goto error;
939 } else
940 PyErr_Clear();
941 msg_str = PyObject_Str(v);
942 if (msg_str)
943 PyUnicode_AppendAndDel(&s, msg_str);
944 else {
945 PyErr_Clear();
946 PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 }
Victor Stinner67002af2011-10-02 20:35:10 +0200948 if (s == NULL)
949 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 PyErr_SetObject(exc_class, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000951error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 Py_XDECREF(tp);
953 Py_XDECREF(v);
954 Py_XDECREF(tb);
955 Py_XDECREF(s);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000956}
957
958
959#ifdef MS_WIN32
960
961static PyObject *
962GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk)
963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 HRESULT hr;
965 ISupportErrorInfo *psei = NULL;
966 IErrorInfo *pei = NULL;
967 BSTR descr=NULL, helpfile=NULL, source=NULL;
968 GUID guid;
969 DWORD helpcontext=0;
970 LPOLESTR progid;
971 PyObject *obj;
972 LPOLESTR text;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 /* We absolutely have to release the GIL during COM method calls,
975 otherwise we may get a deadlock!
976 */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000977#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 Py_BEGIN_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000979#endif
980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei);
982 if (FAILED(hr))
983 goto failed;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid);
986 psei->lpVtbl->Release(psei);
987 if (FAILED(hr))
988 goto failed;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 hr = GetErrorInfo(0, &pei);
991 if (hr != S_OK)
992 goto failed;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 pei->lpVtbl->GetDescription(pei, &descr);
995 pei->lpVtbl->GetGUID(pei, &guid);
996 pei->lpVtbl->GetHelpContext(pei, &helpcontext);
997 pei->lpVtbl->GetHelpFile(pei, &helpfile);
998 pei->lpVtbl->GetSource(pei, &source);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 pei->lpVtbl->Release(pei);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001001
Thomas Hellerd4c93202006-03-08 19:35:11 +00001002 failed:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001003#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 Py_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001005#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 progid = NULL;
1008 ProgIDFromCLSID(&guid, &progid);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 text = FormatError(errcode);
1011 obj = Py_BuildValue(
1012 "iu(uuuiu)",
1013 errcode,
1014 text,
1015 descr, source, helpfile, helpcontext,
1016 progid);
1017 if (obj) {
1018 PyErr_SetObject(ComError, obj);
1019 Py_DECREF(obj);
1020 }
1021 LocalFree(text);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 if (descr)
1024 SysFreeString(descr);
1025 if (helpfile)
1026 SysFreeString(helpfile);
1027 if (source)
1028 SysFreeString(source);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001031}
1032#endif
1033
1034/*
1035 * Requirements, must be ensured by the caller:
1036 * - argtuple is tuple of arguments
1037 * - argtypes is either NULL, or a tuple of the same size as argtuple
1038 *
1039 * - XXX various requirements for restype, not yet collected
1040 */
Thomas Heller34596a92009-04-24 20:50:00 +00001041PyObject *_ctypes_callproc(PPROC pProc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 PyObject *argtuple,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001043#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 IUnknown *pIunk,
1045 GUID *iid,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001046#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 int flags,
1048 PyObject *argtypes, /* misleading name: This is a tuple of
1049 methods, not types: the .from_param
1050 class methods of the types */
1051 PyObject *restype,
1052 PyObject *checker)
Thomas Hellerd4c93202006-03-08 19:35:11 +00001053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 Py_ssize_t i, n, argcount, argtype_count;
1055 void *resbuf;
1056 struct argument *args, *pa;
1057 ffi_type **atypes;
1058 ffi_type *rtype;
1059 void **avalues;
1060 PyObject *retval = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 n = argcount = PyTuple_GET_SIZE(argtuple);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001063#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 /* an optional COM object this pointer */
1065 if (pIunk)
1066 ++argcount;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001067#endif
1068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 args = (struct argument *)alloca(sizeof(struct argument) * argcount);
1070 if (!args) {
1071 PyErr_NoMemory();
1072 return NULL;
1073 }
1074 memset(args, 0, sizeof(struct argument) * argcount);
1075 argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001076#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 if (pIunk) {
1078 args[0].ffi_type = &ffi_type_pointer;
1079 args[0].value.p = pIunk;
1080 pa = &args[1];
1081 } else
Thomas Hellerd4c93202006-03-08 19:35:11 +00001082#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 pa = &args[0];
Thomas Hellerd4c93202006-03-08 19:35:11 +00001084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 /* Convert the arguments */
1086 for (i = 0; i < n; ++i, ++pa) {
1087 PyObject *converter;
1088 PyObject *arg;
1089 int err;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */
1092 /* For cdecl functions, we allow more actual arguments
1093 than the length of the argtypes tuple.
1094 This is checked in _ctypes::PyCFuncPtr_Call
1095 */
1096 if (argtypes && argtype_count > i) {
1097 PyObject *v;
1098 converter = PyTuple_GET_ITEM(argtypes, i);
1099 v = PyObject_CallFunctionObjArgs(converter,
1100 arg,
1101 NULL);
1102 if (v == NULL) {
1103 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1104 goto cleanup;
1105 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 err = ConvParam(v, i+1, pa);
1108 Py_DECREF(v);
1109 if (-1 == err) {
1110 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1111 goto cleanup;
1112 }
1113 } else {
1114 err = ConvParam(arg, i+1, pa);
1115 if (-1 == err) {
1116 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
1117 goto cleanup; /* leaking ? */
1118 }
1119 }
1120 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 rtype = _ctypes_get_ffi_type(restype);
1123 resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));
Thomas Hellerd4c93202006-03-08 19:35:11 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 avalues = (void **)alloca(sizeof(void *) * argcount);
1126 atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
1127 if (!resbuf || !avalues || !atypes) {
1128 PyErr_NoMemory();
1129 goto cleanup;
1130 }
1131 for (i = 0; i < argcount; ++i) {
1132 atypes[i] = args[i].ffi_type;
Victor Stinner4c2e4fa2010-09-29 10:37:16 +00001133 if (atypes[i]->type == FFI_TYPE_STRUCT
Thomas Hellerb00697e2010-06-21 16:00:31 +00001134#ifdef _WIN64
1135 && atypes[i]->size <= sizeof(void *)
1136#endif
1137 )
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 avalues[i] = (void *)args[i].value.p;
1139 else
1140 avalues[i] = (void *)&args[i].value;
1141 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (-1 == _call_function_pointer(flags, pProc, avalues, atypes,
1144 rtype, resbuf,
1145 Py_SAFE_DOWNCAST(argcount,
1146 Py_ssize_t,
1147 int)))
1148 goto cleanup;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001149
1150#ifdef WORDS_BIGENDIAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 /* libffi returns the result in a buffer with sizeof(ffi_arg). This
1152 causes problems on big endian machines, since the result buffer
1153 address cannot simply be used as result pointer, instead we must
1154 adjust the pointer value:
1155 */
1156 /*
1157 XXX I should find out and clarify why this is needed at all,
1158 especially why adjusting for ffi_type_float must be avoided on
1159 64-bit platforms.
1160 */
1161 if (rtype->type != FFI_TYPE_FLOAT
1162 && rtype->type != FFI_TYPE_STRUCT
1163 && rtype->size < sizeof(ffi_arg))
1164 resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001165#endif
1166
1167#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (iid && pIunk) {
1169 if (*(int *)resbuf & 0x80000000)
1170 retval = GetComError(*(HRESULT *)resbuf, iid, pIunk);
1171 else
1172 retval = PyLong_FromLong(*(int *)resbuf);
1173 } else if (flags & FUNCFLAG_HRESULT) {
1174 if (*(int *)resbuf & 0x80000000)
1175 retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
1176 else
1177 retval = PyLong_FromLong(*(int *)resbuf);
1178 } else
Thomas Hellerd4c93202006-03-08 19:35:11 +00001179#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 retval = GetResult(restype, resbuf, checker);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001181 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 for (i = 0; i < argcount; ++i)
1183 Py_XDECREF(args[i].keep);
1184 return retval;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001185}
1186
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001187static int
1188_parse_voidp(PyObject *obj, void **address)
1189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 *address = PyLong_AsVoidPtr(obj);
1191 if (*address == NULL)
1192 return 0;
1193 return 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001194}
1195
Thomas Hellerd4c93202006-03-08 19:35:11 +00001196#ifdef MS_WIN32
1197
Thomas Hellerd4c93202006-03-08 19:35:11 +00001198static char format_error_doc[] =
1199"FormatError([integer]) -> string\n\
1200\n\
1201Convert a win32 error code into a string. If the error code is not\n\
1202given, the return value of a call to GetLastError() is used.\n";
1203static PyObject *format_error(PyObject *self, PyObject *args)
1204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 PyObject *result;
1206 wchar_t *lpMsgBuf;
1207 DWORD code = 0;
1208 if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
1209 return NULL;
1210 if (code == 0)
1211 code = GetLastError();
1212 lpMsgBuf = FormatError(code);
1213 if (lpMsgBuf) {
1214 result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf));
1215 LocalFree(lpMsgBuf);
1216 } else {
1217 result = PyUnicode_FromString("<no description>");
1218 }
1219 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001220}
1221
1222static char load_library_doc[] =
1223"LoadLibrary(name) -> handle\n\
1224\n\
1225Load an executable (usually a DLL), and return a handle to it.\n\
1226The handle may be used to locate exported functions in this\n\
1227module.\n";
1228static PyObject *load_library(PyObject *self, PyObject *args)
1229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 WCHAR *name;
1231 PyObject *nameobj;
1232 PyObject *ignored;
1233 HMODULE hMod;
1234 if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
1235 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 name = PyUnicode_AsUnicode(nameobj);
1238 if (!name)
1239 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 hMod = LoadLibraryW(name);
1242 if (!hMod)
1243 return PyErr_SetFromWindowsErr(GetLastError());
Thomas Wouters89f507f2006-12-13 04:49:30 +00001244#ifdef _WIN64
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 return PyLong_FromVoidPtr(hMod);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001246#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 return Py_BuildValue("i", hMod);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001248#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +00001249}
1250
1251static char free_library_doc[] =
1252"FreeLibrary(handle) -> void\n\
1253\n\
1254Free the handle of an executable previously loaded by LoadLibrary.\n";
1255static PyObject *free_library(PyObject *self, PyObject *args)
1256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 void *hMod;
1258 if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
1259 return NULL;
1260 if (!FreeLibrary((HMODULE)hMod))
1261 return PyErr_SetFromWindowsErr(GetLastError());
1262 Py_INCREF(Py_None);
1263 return Py_None;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001264}
1265
1266/* obsolete, should be removed */
1267/* Only used by sample code (in samples\Windows\COM.py) */
1268static PyObject *
1269call_commethod(PyObject *self, PyObject *args)
1270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 IUnknown *pIunk;
1272 int index;
1273 PyObject *arguments;
1274 PPROC *lpVtbl;
1275 PyObject *result;
1276 CDataObject *pcom;
1277 PyObject *argtypes = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (!PyArg_ParseTuple(args,
1280 "OiO!|O!",
1281 &pcom, &index,
1282 &PyTuple_Type, &arguments,
1283 &PyTuple_Type, &argtypes))
1284 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) {
1287 PyErr_Format(PyExc_TypeError,
1288 "Method takes %d arguments (%d given)",
1289 PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments));
1290 return NULL;
1291 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) {
1294 PyErr_Format(PyExc_TypeError,
1295 "COM Pointer expected instead of %s instance",
1296 Py_TYPE(pcom)->tp_name);
1297 return NULL;
1298 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 if ((*(void **)(pcom->b_ptr)) == NULL) {
1301 PyErr_SetString(PyExc_ValueError,
1302 "The COM 'this' pointer is NULL");
1303 return NULL;
1304 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 pIunk = (IUnknown *)(*(void **)(pcom->b_ptr));
1307 lpVtbl = (PPROC *)(pIunk->lpVtbl);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 result = _ctypes_callproc(lpVtbl[index],
1310 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001311#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 pIunk,
1313 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001314#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 FUNCFLAG_HRESULT, /* flags */
1316 argtypes, /* self->argtypes */
1317 NULL, /* self->restype */
1318 NULL); /* checker */
1319 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001320}
1321
1322static char copy_com_pointer_doc[] =
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001323"CopyComPointer(src, dst) -> HRESULT value\n";
Thomas Hellerd4c93202006-03-08 19:35:11 +00001324
1325static PyObject *
1326copy_com_pointer(PyObject *self, PyObject *args)
1327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 PyObject *p1, *p2, *r = NULL;
1329 struct argument a, b;
1330 IUnknown *src, **pdst;
1331 if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
1332 return NULL;
1333 a.keep = b.keep = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b))
1336 goto done;
1337 src = (IUnknown *)a.value.p;
1338 pdst = (IUnknown **)b.value.p;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 if (pdst == NULL)
1341 r = PyLong_FromLong(E_POINTER);
1342 else {
1343 if (src)
1344 src->lpVtbl->AddRef(src);
1345 *pdst = src;
1346 r = PyLong_FromLong(S_OK);
1347 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001348 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 Py_XDECREF(a.keep);
1350 Py_XDECREF(b.keep);
1351 return r;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001352}
1353#else
1354
1355static PyObject *py_dl_open(PyObject *self, PyObject *args)
1356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 PyObject *name, *name2;
1358 char *name_str;
1359 void * handle;
1360#ifdef RTLD_LOCAL
1361 int mode = RTLD_NOW | RTLD_LOCAL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001362#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 /* cygwin doesn't define RTLD_LOCAL */
1364 int mode = RTLD_NOW;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001365#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode))
1367 return NULL;
1368 mode |= RTLD_NOW;
1369 if (name != Py_None) {
1370 if (PyUnicode_FSConverter(name, &name2) == 0)
1371 return NULL;
1372 if (PyBytes_Check(name2))
1373 name_str = PyBytes_AS_STRING(name2);
1374 else
1375 name_str = PyByteArray_AS_STRING(name2);
1376 } else {
1377 name_str = NULL;
1378 name2 = NULL;
1379 }
1380 handle = ctypes_dlopen(name_str, mode);
1381 Py_XDECREF(name2);
1382 if (!handle) {
1383 char *errmsg = ctypes_dlerror();
1384 if (!errmsg)
1385 errmsg = "dlopen() error";
1386 PyErr_SetString(PyExc_OSError,
1387 errmsg);
1388 return NULL;
1389 }
1390 return PyLong_FromVoidPtr(handle);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001391}
1392
1393static PyObject *py_dl_close(PyObject *self, PyObject *args)
1394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 void *handle;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
1398 return NULL;
1399 if (dlclose(handle)) {
1400 PyErr_SetString(PyExc_OSError,
1401 ctypes_dlerror());
1402 return NULL;
1403 }
1404 Py_INCREF(Py_None);
1405 return Py_None;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001406}
1407
1408static PyObject *py_dl_sym(PyObject *self, PyObject *args)
1409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 char *name;
1411 void *handle;
1412 void *ptr;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 if (!PyArg_ParseTuple(args, "O&s:dlsym",
1415 &_parse_voidp, &handle, &name))
1416 return NULL;
1417 ptr = ctypes_dlsym((void*)handle, name);
1418 if (!ptr) {
1419 PyErr_SetString(PyExc_OSError,
1420 ctypes_dlerror());
1421 return NULL;
1422 }
1423 return PyLong_FromVoidPtr(ptr);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001424}
1425#endif
1426
1427/*
1428 * Only for debugging so far: So that we can call CFunction instances
1429 *
1430 * XXX Needs to accept more arguments: flags, argtypes, restype
1431 */
1432static PyObject *
1433call_function(PyObject *self, PyObject *args)
1434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 void *func;
1436 PyObject *arguments;
1437 PyObject *result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 if (!PyArg_ParseTuple(args,
1440 "O&O!",
1441 &_parse_voidp, &func,
1442 &PyTuple_Type, &arguments))
1443 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 result = _ctypes_callproc((PPROC)func,
1446 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001447#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 NULL,
1449 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001450#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 0, /* flags */
1452 NULL, /* self->argtypes */
1453 NULL, /* self->restype */
1454 NULL); /* checker */
1455 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001456}
1457
1458/*
1459 * Only for debugging so far: So that we can call CFunction instances
1460 *
1461 * XXX Needs to accept more arguments: flags, argtypes, restype
1462 */
1463static PyObject *
1464call_cdeclfunction(PyObject *self, PyObject *args)
1465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 void *func;
1467 PyObject *arguments;
1468 PyObject *result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 if (!PyArg_ParseTuple(args,
1471 "O&O!",
1472 &_parse_voidp, &func,
1473 &PyTuple_Type, &arguments))
1474 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 result = _ctypes_callproc((PPROC)func,
1477 arguments,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001478#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 NULL,
1480 NULL,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001481#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 FUNCFLAG_CDECL, /* flags */
1483 NULL, /* self->argtypes */
1484 NULL, /* self->restype */
1485 NULL); /* checker */
1486 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001487}
1488
1489/*****************************************************************
1490 * functions
1491 */
1492static char sizeof_doc[] =
1493"sizeof(C type) -> integer\n"
1494"sizeof(C instance) -> integer\n"
1495"Return the size in bytes of a C instance";
1496
1497static PyObject *
1498sizeof_func(PyObject *self, PyObject *obj)
1499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 StgDictObject *dict;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 dict = PyType_stgdict(obj);
1503 if (dict)
1504 return PyLong_FromSsize_t(dict->size);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (CDataObject_Check(obj))
1507 return PyLong_FromSsize_t(((CDataObject *)obj)->b_size);
1508 PyErr_SetString(PyExc_TypeError,
1509 "this type has no size");
1510 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001511}
1512
1513static char alignment_doc[] =
1514"alignment(C type) -> integer\n"
1515"alignment(C instance) -> integer\n"
1516"Return the alignment requirements of a C instance";
1517
1518static PyObject *
1519align_func(PyObject *self, PyObject *obj)
1520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 StgDictObject *dict;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 dict = PyType_stgdict(obj);
1524 if (dict)
1525 return PyLong_FromSsize_t(dict->align);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 dict = PyObject_stgdict(obj);
1528 if (dict)
1529 return PyLong_FromSsize_t(dict->align);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 PyErr_SetString(PyExc_TypeError,
1532 "no alignment info");
1533 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001534}
1535
1536static char byref_doc[] =
Thomas Hellerc5d01262008-06-10 15:08:51 +00001537"byref(C instance[, offset=0]) -> byref-object\n"
Thomas Hellerd4c93202006-03-08 19:35:11 +00001538"Return a pointer lookalike to a C instance, only usable\n"
1539"as function argument";
1540
1541/*
1542 * We must return something which can be converted to a parameter,
1543 * but still has a reference to self.
1544 */
1545static PyObject *
Thomas Hellerc5d01262008-06-10 15:08:51 +00001546byref(PyObject *self, PyObject *args)
Thomas Hellerd4c93202006-03-08 19:35:11 +00001547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 PyCArgObject *parg;
1549 PyObject *obj;
1550 PyObject *pyoffset = NULL;
1551 Py_ssize_t offset = 0;
Thomas Hellerc5d01262008-06-10 15:08:51 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 if (!PyArg_UnpackTuple(args, "byref", 1, 2,
1554 &obj, &pyoffset))
1555 return NULL;
1556 if (pyoffset) {
1557 offset = PyNumber_AsSsize_t(pyoffset, NULL);
1558 if (offset == -1 && PyErr_Occurred())
1559 return NULL;
1560 }
1561 if (!CDataObject_Check(obj)) {
1562 PyErr_Format(PyExc_TypeError,
1563 "byref() argument must be a ctypes instance, not '%s'",
1564 Py_TYPE(obj)->tp_name);
1565 return NULL;
1566 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 parg = PyCArgObject_new();
1569 if (parg == NULL)
1570 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 parg->tag = 'P';
1573 parg->pffi_type = &ffi_type_pointer;
1574 Py_INCREF(obj);
1575 parg->obj = obj;
1576 parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
1577 return (PyObject *)parg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001578}
1579
1580static char addressof_doc[] =
1581"addressof(C instance) -> integer\n"
1582"Return the address of the C instance internal buffer";
1583
1584static PyObject *
1585addressof(PyObject *self, PyObject *obj)
1586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 if (CDataObject_Check(obj))
1588 return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
1589 PyErr_SetString(PyExc_TypeError,
1590 "invalid type");
1591 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001592}
1593
1594static int
1595converter(PyObject *obj, void **address)
1596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 *address = PyLong_AsVoidPtr(obj);
1598 return *address != NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001599}
1600
1601static PyObject *
1602My_PyObj_FromPtr(PyObject *self, PyObject *args)
1603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 PyObject *ob;
1605 if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob))
1606 return NULL;
1607 Py_INCREF(ob);
1608 return ob;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001609}
1610
1611static PyObject *
1612My_Py_INCREF(PyObject *self, PyObject *arg)
1613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 Py_INCREF(arg); /* that's what this function is for */
1615 Py_INCREF(arg); /* that for returning it */
1616 return arg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001617}
1618
1619static PyObject *
1620My_Py_DECREF(PyObject *self, PyObject *arg)
1621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 Py_DECREF(arg); /* that's what this function is for */
1623 Py_INCREF(arg); /* that's for returning it */
1624 return arg;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001625}
1626
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001627static PyObject *
1628resize(PyObject *self, PyObject *args)
1629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 CDataObject *obj;
1631 StgDictObject *dict;
1632 Py_ssize_t size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 if (!PyArg_ParseTuple(args,
1635 "On:resize",
1636 &obj, &size))
1637 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 dict = PyObject_stgdict((PyObject *)obj);
1640 if (dict == NULL) {
1641 PyErr_SetString(PyExc_TypeError,
1642 "excepted ctypes instance");
1643 return NULL;
1644 }
1645 if (size < dict->size) {
1646 PyErr_Format(PyExc_ValueError,
1647 "minimum size is %zd",
1648 dict->size);
1649 return NULL;
1650 }
1651 if (obj->b_needsfree == 0) {
1652 PyErr_Format(PyExc_ValueError,
1653 "Memory cannot be resized because this object doesn't own it");
1654 return NULL;
1655 }
1656 if (size <= sizeof(obj->b_value)) {
1657 /* internal default buffer is large enough */
1658 obj->b_size = size;
1659 goto done;
1660 }
1661 if (obj->b_size <= sizeof(obj->b_value)) {
1662 /* We are currently using the objects default buffer, but it
1663 isn't large enough any more. */
1664 void *ptr = PyMem_Malloc(size);
1665 if (ptr == NULL)
1666 return PyErr_NoMemory();
1667 memset(ptr, 0, size);
1668 memmove(ptr, obj->b_ptr, obj->b_size);
1669 obj->b_ptr = ptr;
1670 obj->b_size = size;
1671 } else {
1672 void * ptr = PyMem_Realloc(obj->b_ptr, size);
1673 if (ptr == NULL)
1674 return PyErr_NoMemory();
1675 obj->b_ptr = ptr;
1676 obj->b_size = size;
1677 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001678 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 Py_INCREF(Py_None);
1680 return Py_None;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001681}
1682
Thomas Heller13394e92008-02-13 20:40:44 +00001683static PyObject *
1684unpickle(PyObject *self, PyObject *args)
1685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 PyObject *typ;
1687 PyObject *state;
1688 PyObject *result;
1689 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001690 _Py_IDENTIFIER(__new__);
1691 _Py_IDENTIFIER(__setstate__);
Thomas Heller13394e92008-02-13 20:40:44 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (!PyArg_ParseTuple(args, "OO", &typ, &state))
1694 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001695 result = _PyObject_CallMethodId(typ, &PyId___new__, "O", typ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 if (result == NULL)
1697 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001698 tmp = _PyObject_CallMethodId(result, &PyId___setstate__, "O", state);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 if (tmp == NULL) {
1700 Py_DECREF(result);
1701 return NULL;
1702 }
1703 Py_DECREF(tmp);
1704 return result;
Thomas Heller13394e92008-02-13 20:40:44 +00001705}
1706
Thomas Heller3071f812008-04-14 16:17:33 +00001707static PyObject *
1708POINTER(PyObject *self, PyObject *cls)
1709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 PyObject *result;
1711 PyTypeObject *typ;
1712 PyObject *key;
1713 char *buf;
Thomas Heller3071f812008-04-14 16:17:33 +00001714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 result = PyDict_GetItem(_ctypes_ptrtype_cache, cls);
1716 if (result) {
1717 Py_INCREF(result);
1718 return result;
1719 }
1720 if (PyUnicode_CheckExact(cls)) {
1721 char *name = _PyUnicode_AsString(cls);
1722 buf = alloca(strlen(name) + 3 + 1);
1723 sprintf(buf, "LP_%s", name);
1724 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
1725 "s(O){}",
1726 buf,
1727 &PyCPointer_Type);
1728 if (result == NULL)
1729 return result;
1730 key = PyLong_FromVoidPtr(result);
1731 } else if (PyType_Check(cls)) {
1732 typ = (PyTypeObject *)cls;
1733 buf = alloca(strlen(typ->tp_name) + 3 + 1);
1734 sprintf(buf, "LP_%s", typ->tp_name);
1735 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
1736 "s(O){sO}",
1737 buf,
1738 &PyCPointer_Type,
1739 "_type_", cls);
1740 if (result == NULL)
1741 return result;
1742 Py_INCREF(cls);
1743 key = cls;
1744 } else {
1745 PyErr_SetString(PyExc_TypeError, "must be a ctypes type");
1746 return NULL;
1747 }
1748 if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) {
1749 Py_DECREF(result);
1750 Py_DECREF(key);
1751 return NULL;
1752 }
1753 Py_DECREF(key);
1754 return result;
Thomas Heller3071f812008-04-14 16:17:33 +00001755}
1756
1757static PyObject *
1758pointer(PyObject *self, PyObject *arg)
1759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 PyObject *result;
1761 PyObject *typ;
Thomas Heller3071f812008-04-14 16:17:33 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg));
1764 if (typ)
1765 return PyObject_CallFunctionObjArgs(typ, arg, NULL);
1766 typ = POINTER(NULL, (PyObject *)Py_TYPE(arg));
1767 if (typ == NULL)
1768 return NULL;
1769 result = PyObject_CallFunctionObjArgs(typ, arg, NULL);
1770 Py_DECREF(typ);
1771 return result;
Thomas Heller3071f812008-04-14 16:17:33 +00001772}
1773
Thomas Hellerb041fda2008-04-30 17:11:46 +00001774static PyObject *
1775buffer_info(PyObject *self, PyObject *arg)
1776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 StgDictObject *dict = PyType_stgdict(arg);
1778 PyObject *shape;
1779 Py_ssize_t i;
Thomas Hellerb041fda2008-04-30 17:11:46 +00001780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 if (dict == NULL)
1782 dict = PyObject_stgdict(arg);
1783 if (dict == NULL) {
1784 PyErr_SetString(PyExc_TypeError,
1785 "not a ctypes type or object");
1786 return NULL;
1787 }
1788 shape = PyTuple_New(dict->ndim);
1789 if (shape == NULL)
1790 return NULL;
1791 for (i = 0; i < (int)dict->ndim; ++i)
1792 PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i]));
Thomas Hellerb041fda2008-04-30 17:11:46 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 if (PyErr_Occurred()) {
1795 Py_DECREF(shape);
1796 return NULL;
1797 }
1798 return Py_BuildValue("siN", dict->format, dict->ndim, shape);
Thomas Hellerb041fda2008-04-30 17:11:46 +00001799}
1800
Thomas Heller34596a92009-04-24 20:50:00 +00001801PyMethodDef _ctypes_module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 {"get_errno", get_errno, METH_NOARGS},
1803 {"set_errno", set_errno, METH_VARARGS},
1804 {"POINTER", POINTER, METH_O },
1805 {"pointer", pointer, METH_O },
1806 {"_unpickle", unpickle, METH_VARARGS },
1807 {"buffer_info", buffer_info, METH_O, "Return buffer interface information"},
1808 {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001809#ifdef MS_WIN32
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 {"get_last_error", get_last_error, METH_NOARGS},
1811 {"set_last_error", set_last_error, METH_VARARGS},
1812 {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
1813 {"FormatError", format_error, METH_VARARGS, format_error_doc},
1814 {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
1815 {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
1816 {"call_commethod", call_commethod, METH_VARARGS },
1817 {"_check_HRESULT", check_hresult, METH_VARARGS},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001818#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 {"dlopen", py_dl_open, METH_VARARGS,
1820 "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
1821 {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
1822 {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001823#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 {"alignment", align_func, METH_O, alignment_doc},
1825 {"sizeof", sizeof_func, METH_O, sizeof_doc},
1826 {"byref", byref, METH_VARARGS, byref_doc},
1827 {"addressof", addressof, METH_O, addressof_doc},
1828 {"call_function", call_function, METH_VARARGS },
1829 {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
1830 {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
1831 {"Py_INCREF", My_Py_INCREF, METH_O },
1832 {"Py_DECREF", My_Py_DECREF, METH_O },
1833 {NULL, NULL} /* Sentinel */
Thomas Hellerd4c93202006-03-08 19:35:11 +00001834};
1835
1836/*
1837 Local Variables:
1838 compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"
1839 End:
1840*/