blob: cbc5cf86fecacc147ccc41841018fb57ade7659a [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:
7 * - calldll http://www.nightmare.com/software.html
8 * - libffi http://sourceware.cygnus.com/libffi/
9 * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html
10 * and, of course, Don Beaudry's MESS package, but this is more ctypes
11 * related.
12 */
13
14
15/*
16 How are functions called, and how are parameters converted to C ?
17
Thomas Heller34596a92009-04-24 20:50:00 +000018 1. _ctypes.c::PyCFuncPtr_call receives an argument tuple 'inargs' and a
Thomas Hellerd4c93202006-03-08 19:35:11 +000019 keyword dictionary 'kwds'.
20
21 2. After several checks, _build_callargs() is called which returns another
22 tuple 'callargs'. This may be the same tuple as 'inargs', a slice of
23 'inargs', or a completely fresh tuple, depending on several things (is is a
24 COM method, are 'paramflags' available).
25
26 3. _build_callargs also calculates bitarrays containing indexes into
27 the callargs tuple, specifying how to build the return value(s) of
28 the function.
29
Thomas Heller34596a92009-04-24 20:50:00 +000030 4. _ctypes_callproc is then called with the 'callargs' tuple. _ctypes_callproc first
Thomas Hellerd4c93202006-03-08 19:35:11 +000031 allocates two arrays. The first is an array of 'struct argument' items, the
32 second array has 'void *' entried.
33
34 5. If 'converters' are present (converters is a sequence of argtypes'
35 from_param methods), for each item in 'callargs' converter is called and the
36 result passed to ConvParam. If 'converters' are not present, each argument
37 is directly passed to ConvParm.
38
39 6. For each arg, ConvParam stores the contained C data (or a pointer to it,
40 for structures) into the 'struct argument' array.
41
42 7. Finally, a loop fills the 'void *' array so that each item points to the
43 data contained in or pointed to by the 'struct argument' array.
44
45 8. The 'void *' argument array is what _call_function_pointer
46 expects. _call_function_pointer then has very little to do - only some
47 libffi specific stuff, then it calls ffi_call.
48
49 So, there are 4 data structures holding processed arguments:
Thomas Heller34596a92009-04-24 20:50:00 +000050 - the inargs tuple (in PyCFuncPtr_call)
51 - the callargs tuple (in PyCFuncPtr_call)
Thomas Hellerd4c93202006-03-08 19:35:11 +000052 - the 'struct argguments' array
53 - the 'void *' array
54
55 */
56
57#include "Python.h"
58#include "structmember.h"
59
60#ifdef MS_WIN32
61#include <windows.h>
Guido van Rossumd8faa362007-04-27 19:54:29 +000062#include <tchar.h>
Thomas Hellerd4c93202006-03-08 19:35:11 +000063#else
64#include "ctypes_dlfcn.h"
65#endif
66
67#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068#include <malloc.h>
Thomas Hellerd4c93202006-03-08 19:35:11 +000069#endif
70
71#include <ffi.h>
72#include "ctypes.h"
73
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000074#if defined(_DEBUG) || defined(__MINGW32__)
75/* Don't use structured exception handling on Windows if this is defined.
76 MingW, AFAIK, doesn't support it.
77*/
78#define DONT_USE_SEH
Thomas Hellerd4c93202006-03-08 19:35:11 +000079#endif
80
Benjamin Petersonb173f782009-05-05 22:31:58 +000081#define CTYPES_CAPSULE_NAME_PYMEM "_ctypes pymem"
82
83static void pymem_destructor(PyObject *ptr)
84{
85 void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM);
86 if (p) {
87 PyMem_Free(p);
88 }
89}
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.
95
96 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{
128 PyObject *dict = PyThreadState_GetDict();
129 PyObject *errobj;
Thomas Hellerb795f5282008-06-10 15:26:58 +0000130 static PyObject *error_object_name;
Thomas Heller9cac7b62008-06-06 09:31:40 +0000131 if (dict == 0) {
132 PyErr_SetString(PyExc_RuntimeError,
133 "cannot get thread state");
134 return NULL;
135 }
Thomas Hellerb795f5282008-06-10 15:26:58 +0000136 if (error_object_name == NULL) {
Thomas Hellerb1ef6732008-06-10 15:30:51 +0000137 error_object_name = PyUnicode_InternFromString("ctypes.error_object");
Thomas Hellerb795f5282008-06-10 15:26:58 +0000138 if (error_object_name == NULL)
139 return NULL;
140 }
141 errobj = PyDict_GetItem(dict, error_object_name);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000142 if (errobj)
143 Py_INCREF(errobj);
144 else {
145 void *space = PyMem_Malloc(sizeof(int) * 2);
146 if (space == NULL)
147 return NULL;
148 memset(space, 0, sizeof(int) * 2);
Benjamin Petersonb173f782009-05-05 22:31:58 +0000149 errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000150 if (errobj == NULL)
151 return NULL;
Thomas Hellerb795f5282008-06-10 15:26:58 +0000152 if (-1 == PyDict_SetItem(dict, error_object_name,
153 errobj)) {
Thomas Heller9cac7b62008-06-06 09:31:40 +0000154 Py_DECREF(errobj);
155 return NULL;
156 }
157 }
Benjamin Petersonb173f782009-05-05 22:31:58 +0000158 *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000159 return errobj;
160}
161
162static PyObject *
163get_error_internal(PyObject *self, PyObject *args, int index)
164{
165 int *space;
Thomas Heller34596a92009-04-24 20:50:00 +0000166 PyObject *errobj = _ctypes_get_errobj(&space);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000167 PyObject *result;
168
169 if (errobj == NULL)
170 return NULL;
171 result = PyLong_FromLong(space[index]);
172 Py_DECREF(errobj);
173 return result;
174}
175
176static PyObject *
177set_error_internal(PyObject *self, PyObject *args, int index)
178{
179 int new_errno, old_errno;
180 PyObject *errobj;
181 int *space;
182
183 if (!PyArg_ParseTuple(args, "i", &new_errno))
184 return NULL;
Thomas Heller34596a92009-04-24 20:50:00 +0000185 errobj = _ctypes_get_errobj(&space);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000186 if (errobj == NULL)
187 return NULL;
188 old_errno = space[index];
189 space[index] = new_errno;
190 Py_DECREF(errobj);
191 return PyLong_FromLong(old_errno);
192}
193
194static PyObject *
195get_errno(PyObject *self, PyObject *args)
196{
197 return get_error_internal(self, args, 0);
198}
199
200static PyObject *
201set_errno(PyObject *self, PyObject *args)
202{
203 return set_error_internal(self, args, 0);
204}
205
Thomas Hellerd4c93202006-03-08 19:35:11 +0000206#ifdef MS_WIN32
Thomas Heller9cac7b62008-06-06 09:31:40 +0000207
208static PyObject *
209get_last_error(PyObject *self, PyObject *args)
210{
211 return get_error_internal(self, args, 1);
212}
213
214static PyObject *
215set_last_error(PyObject *self, PyObject *args)
216{
217 return set_error_internal(self, args, 1);
218}
219
Thomas Hellerd4c93202006-03-08 19:35:11 +0000220PyObject *ComError;
221
Thomas Heller71fb5132008-11-26 08:45:36 +0000222static WCHAR *FormatError(DWORD code)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000223{
Thomas Heller71fb5132008-11-26 08:45:36 +0000224 WCHAR *lpMsgBuf;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000225 DWORD n;
Thomas Heller71fb5132008-11-26 08:45:36 +0000226 n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
227 NULL,
228 code,
Christian Heimesd74a1dc2008-12-03 00:55:34 +0000229 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
Thomas Heller71fb5132008-11-26 08:45:36 +0000230 (LPWSTR) &lpMsgBuf,
231 0,
232 NULL);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000233 if (n) {
Thomas Heller71fb5132008-11-26 08:45:36 +0000234 while (iswspace(lpMsgBuf[n-1]))
Thomas Hellerd4c93202006-03-08 19:35:11 +0000235 --n;
Thomas Heller71fb5132008-11-26 08:45:36 +0000236 lpMsgBuf[n] = L'\0'; /* rstrip() */
Thomas Hellerd4c93202006-03-08 19:35:11 +0000237 }
238 return lpMsgBuf;
239}
240
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000241#ifndef DONT_USE_SEH
Thomas Heller84c97af2009-04-25 16:49:23 +0000242static void SetException(DWORD code, EXCEPTION_RECORD *pr)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000243{
Thomas Heller84c97af2009-04-25 16:49:23 +0000244 /* The 'code' is a normal win32 error code so it could be handled by
245 PyErr_SetFromWindowsErr(). However, for some errors, we have additional
246 information not included in the error code. We handle those here and
247 delegate all others to the generic function. */
248 switch (code) {
249 case EXCEPTION_ACCESS_VIOLATION:
250 /* The thread attempted to read from or write
251 to a virtual address for which it does not
252 have the appropriate access. */
253 if (pr->ExceptionInformation[0] == 0)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000254 PyErr_Format(PyExc_WindowsError,
Thomas Heller84c97af2009-04-25 16:49:23 +0000255 "exception: access violation reading %p",
256 pr->ExceptionInformation[1]);
257 else
258 PyErr_Format(PyExc_WindowsError,
259 "exception: access violation writing %p",
260 pr->ExceptionInformation[1]);
261 break;
262
263 case EXCEPTION_BREAKPOINT:
264 /* A breakpoint was encountered. */
265 PyErr_SetString(PyExc_WindowsError,
266 "exception: breakpoint encountered");
267 break;
268
269 case EXCEPTION_DATATYPE_MISALIGNMENT:
270 /* The thread attempted to read or write data that is
271 misaligned on hardware that does not provide
272 alignment. For example, 16-bit values must be
273 aligned on 2-byte boundaries, 32-bit values on
274 4-byte boundaries, and so on. */
275 PyErr_SetString(PyExc_WindowsError,
276 "exception: datatype misalignment");
277 break;
278
279 case EXCEPTION_SINGLE_STEP:
280 /* A trace trap or other single-instruction mechanism
281 signaled that one instruction has been executed. */
282 PyErr_SetString(PyExc_WindowsError,
283 "exception: single step");
284 break;
285
286 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
287 /* The thread attempted to access an array element
288 that is out of bounds, and the underlying hardware
289 supports bounds checking. */
290 PyErr_SetString(PyExc_WindowsError,
291 "exception: array bounds exceeded");
292 break;
293
294 case EXCEPTION_FLT_DENORMAL_OPERAND:
295 /* One of the operands in a floating-point operation
296 is denormal. A denormal value is one that is too
297 small to represent as a standard floating-point
298 value. */
299 PyErr_SetString(PyExc_WindowsError,
300 "exception: floating-point operand denormal");
301 break;
302
303 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
304 /* The thread attempted to divide a floating-point
305 value by a floating-point divisor of zero. */
306 PyErr_SetString(PyExc_WindowsError,
307 "exception: float divide by zero");
308 break;
309
310 case EXCEPTION_FLT_INEXACT_RESULT:
311 /* The result of a floating-point operation cannot be
312 represented exactly as a decimal fraction. */
313 PyErr_SetString(PyExc_WindowsError,
314 "exception: float inexact");
315 break;
316
317 case EXCEPTION_FLT_INVALID_OPERATION:
318 /* This exception represents any floating-point
319 exception not included in this list. */
320 PyErr_SetString(PyExc_WindowsError,
321 "exception: float invalid operation");
322 break;
323
324 case EXCEPTION_FLT_OVERFLOW:
325 /* The exponent of a floating-point operation is
326 greater than the magnitude allowed by the
327 corresponding type. */
328 PyErr_SetString(PyExc_WindowsError,
329 "exception: float overflow");
330 break;
331
332 case EXCEPTION_FLT_STACK_CHECK:
333 /* The stack overflowed or underflowed as the result
334 of a floating-point operation. */
335 PyErr_SetString(PyExc_WindowsError,
336 "exception: stack over/underflow");
337 break;
338
339 case EXCEPTION_STACK_OVERFLOW:
340 /* The stack overflowed or underflowed as the result
341 of a floating-point operation. */
342 PyErr_SetString(PyExc_WindowsError,
343 "exception: stack overflow");
344 break;
345
346 case EXCEPTION_FLT_UNDERFLOW:
347 /* The exponent of a floating-point operation is less
348 than the magnitude allowed by the corresponding
349 type. */
350 PyErr_SetString(PyExc_WindowsError,
351 "exception: float underflow");
352 break;
353
354 case EXCEPTION_INT_DIVIDE_BY_ZERO:
355 /* The thread attempted to divide an integer value by
356 an integer divisor of zero. */
357 PyErr_SetString(PyExc_WindowsError,
358 "exception: integer divide by zero");
359 break;
360
361 case EXCEPTION_INT_OVERFLOW:
362 /* The result of an integer operation caused a carry
363 out of the most significant bit of the result. */
364 PyErr_SetString(PyExc_WindowsError,
365 "exception: integer overflow");
366 break;
367
368 case EXCEPTION_PRIV_INSTRUCTION:
369 /* The thread attempted to execute an instruction
370 whose operation is not allowed in the current
371 machine mode. */
372 PyErr_SetString(PyExc_WindowsError,
373 "exception: priviledged instruction");
374 break;
375
376 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
377 /* The thread attempted to continue execution after a
378 noncontinuable exception occurred. */
379 PyErr_SetString(PyExc_WindowsError,
380 "exception: nocontinuable");
381 break;
382
383 default:
384 PyErr_SetFromWindowsErr(code);
385 break;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000386 }
387}
388
389static DWORD HandleException(EXCEPTION_POINTERS *ptrs,
390 DWORD *pdw, EXCEPTION_RECORD *record)
391{
392 *pdw = ptrs->ExceptionRecord->ExceptionCode;
393 *record = *ptrs->ExceptionRecord;
394 return EXCEPTION_EXECUTE_HANDLER;
395}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000396#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +0000397
398static PyObject *
399check_hresult(PyObject *self, PyObject *args)
400{
401 HRESULT hr;
402 if (!PyArg_ParseTuple(args, "i", &hr))
403 return NULL;
404 if (FAILED(hr))
405 return PyErr_SetFromWindowsErr(hr);
Christian Heimes217cfd12007-12-02 14:31:20 +0000406 return PyLong_FromLong(hr);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000407}
408
409#endif
410
411/**************************************************************/
412
413PyCArgObject *
Thomas Heller34596a92009-04-24 20:50:00 +0000414PyCArgObject_new(void)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000415{
416 PyCArgObject *p;
417 p = PyObject_New(PyCArgObject, &PyCArg_Type);
418 if (p == NULL)
419 return NULL;
420 p->pffi_type = NULL;
421 p->tag = '\0';
422 p->obj = NULL;
423 memset(&p->value, 0, sizeof(p->value));
424 return p;
425}
426
427static void
428PyCArg_dealloc(PyCArgObject *self)
429{
430 Py_XDECREF(self->obj);
431 PyObject_Del(self);
432}
433
434static PyObject *
435PyCArg_repr(PyCArgObject *self)
436{
437 char buffer[256];
438 switch(self->tag) {
439 case 'b':
440 case 'B':
441 sprintf(buffer, "<cparam '%c' (%d)>",
442 self->tag, self->value.b);
443 break;
444 case 'h':
445 case 'H':
446 sprintf(buffer, "<cparam '%c' (%d)>",
447 self->tag, self->value.h);
448 break;
449 case 'i':
450 case 'I':
451 sprintf(buffer, "<cparam '%c' (%d)>",
452 self->tag, self->value.i);
453 break;
454 case 'l':
455 case 'L':
456 sprintf(buffer, "<cparam '%c' (%ld)>",
457 self->tag, self->value.l);
458 break;
459
460#ifdef HAVE_LONG_LONG
461 case 'q':
462 case 'Q':
463 sprintf(buffer,
464#ifdef MS_WIN32
465 "<cparam '%c' (%I64d)>",
466#else
467 "<cparam '%c' (%qd)>",
468#endif
469 self->tag, self->value.q);
470 break;
471#endif
472 case 'd':
473 sprintf(buffer, "<cparam '%c' (%f)>",
474 self->tag, self->value.d);
475 break;
476 case 'f':
477 sprintf(buffer, "<cparam '%c' (%f)>",
478 self->tag, self->value.f);
479 break;
480
481 case 'c':
482 sprintf(buffer, "<cparam '%c' (%c)>",
483 self->tag, self->value.c);
484 break;
485
486/* Hm, are these 'z' and 'Z' codes useful at all?
487 Shouldn't they be replaced by the functionality of c_string
488 and c_wstring ?
489*/
490 case 'z':
491 case 'Z':
492 case 'P':
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000493 sprintf(buffer, "<cparam '%c' (%p)>",
494 self->tag, self->value.p);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000495 break;
496
497 default:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000498 sprintf(buffer, "<cparam '%c' at %p>",
499 self->tag, self);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000500 break;
501 }
Walter Dörwald1ab83302007-05-18 17:15:44 +0000502 return PyUnicode_FromString(buffer);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000503}
504
505static PyMemberDef PyCArgType_members[] = {
506 { "_obj", T_OBJECT,
507 offsetof(PyCArgObject, obj), READONLY,
508 "the wrapped object" },
509 { NULL },
510};
511
512PyTypeObject PyCArg_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000513 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000514 "CArgObject",
515 sizeof(PyCArgObject),
516 0,
517 (destructor)PyCArg_dealloc, /* tp_dealloc */
518 0, /* tp_print */
519 0, /* tp_getattr */
520 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +0000521 0, /* tp_reserved */
Thomas Hellerd4c93202006-03-08 19:35:11 +0000522 (reprfunc)PyCArg_repr, /* tp_repr */
523 0, /* tp_as_number */
524 0, /* tp_as_sequence */
525 0, /* tp_as_mapping */
526 0, /* tp_hash */
527 0, /* tp_call */
528 0, /* tp_str */
529 0, /* tp_getattro */
530 0, /* tp_setattro */
531 0, /* tp_as_buffer */
532 Py_TPFLAGS_DEFAULT, /* tp_flags */
533 0, /* tp_doc */
534 0, /* tp_traverse */
535 0, /* tp_clear */
536 0, /* tp_richcompare */
537 0, /* tp_weaklistoffset */
538 0, /* tp_iter */
539 0, /* tp_iternext */
540 0, /* tp_methods */
541 PyCArgType_members, /* tp_members */
542};
543
544/****************************************************************/
545/*
546 * Convert a PyObject * into a parameter suitable to pass to an
547 * C function call.
548 *
549 * 1. Python integers are converted to C int and passed by value.
550 *
551 * 2. 3-tuples are expected to have a format character in the first
552 * item, which must be 'i', 'f', 'd', 'q', or 'P'.
553 * The second item will have to be an integer, float, double, long long
554 * or integer (denoting an address void *), will be converted to the
555 * corresponding C data type and passed by value.
556 *
557 * 3. Other Python objects are tested for an '_as_parameter_' attribute.
558 * The value of this attribute must be an integer which will be passed
559 * by value, or a 2-tuple or 3-tuple which will be used according
560 * to point 2 above. The third item (if any), is ignored. It is normally
561 * used to keep the object alive where this parameter refers to.
562 * XXX This convention is dangerous - you can construct arbitrary tuples
563 * in Python and pass them. Would it be safer to use a custom container
564 * datatype instead of a tuple?
565 *
566 * 4. Other Python objects cannot be passed as parameters - an exception is raised.
567 *
568 * 5. ConvParam will store the converted result in a struct containing format
569 * and value.
570 */
571
572union result {
573 char c;
574 char b;
575 short h;
576 int i;
577 long l;
578#ifdef HAVE_LONG_LONG
579 PY_LONG_LONG q;
580#endif
Thomas Wouters89d996e2007-09-08 17:39:28 +0000581 long double D;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000582 double d;
583 float f;
584 void *p;
585};
586
587struct argument {
588 ffi_type *ffi_type;
589 PyObject *keep;
590 union result value;
591};
592
593/*
594 * Convert a single Python object into a PyCArgObject and return it.
595 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000596static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000597{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000598 StgDictObject *dict;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000599 pa->keep = NULL; /* so we cannot forget it later */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000600
601 dict = PyObject_stgdict(obj);
602 if (dict) {
603 PyCArgObject *carg;
604 assert(dict->paramfunc);
605 /* If it has an stgdict, it is a CDataObject */
606 carg = dict->paramfunc((CDataObject *)obj);
607 pa->ffi_type = carg->pffi_type;
608 memcpy(&pa->value, &carg->value, sizeof(pa->value));
609 pa->keep = (PyObject *)carg;
610 return 0;
611 }
612
Thomas Hellerd4c93202006-03-08 19:35:11 +0000613 if (PyCArg_CheckExact(obj)) {
614 PyCArgObject *carg = (PyCArgObject *)obj;
615 pa->ffi_type = carg->pffi_type;
616 Py_INCREF(obj);
617 pa->keep = obj;
618 memcpy(&pa->value, &carg->value, sizeof(pa->value));
619 return 0;
620 }
621
622 /* check for None, integer, string or unicode and use directly if successful */
623 if (obj == Py_None) {
624 pa->ffi_type = &ffi_type_pointer;
625 pa->value.p = NULL;
626 return 0;
627 }
628
Thomas Hellerd4c93202006-03-08 19:35:11 +0000629 if (PyLong_Check(obj)) {
630 pa->ffi_type = &ffi_type_sint;
631 pa->value.i = (long)PyLong_AsUnsignedLong(obj);
632 if (pa->value.i == -1 && PyErr_Occurred()) {
633 PyErr_Clear();
634 pa->value.i = PyLong_AsLong(obj);
635 if (pa->value.i == -1 && PyErr_Occurred()) {
636 PyErr_SetString(PyExc_OverflowError,
637 "long int too long to convert");
638 return -1;
639 }
640 }
641 return 0;
642 }
643
Christian Heimes72b710a2008-05-26 13:28:38 +0000644 if (PyBytes_Check(obj)) {
Thomas Heller7775c712007-07-12 19:19:43 +0000645 pa->ffi_type = &ffi_type_pointer;
Christian Heimes72b710a2008-05-26 13:28:38 +0000646 pa->value.p = PyBytes_AsString(obj);
Thomas Heller7775c712007-07-12 19:19:43 +0000647 Py_INCREF(obj);
648 pa->keep = obj;
649 return 0;
650 }
651
Thomas Hellerd4c93202006-03-08 19:35:11 +0000652#ifdef CTYPES_UNICODE
653 if (PyUnicode_Check(obj)) {
Thomas Heller5e4e4272009-01-08 09:34:20 +0000654#ifdef HAVE_USABLE_WCHAR_T
Thomas Heller465c8022009-02-10 18:59:04 +0000655 pa->ffi_type = &ffi_type_pointer;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000656 pa->value.p = PyUnicode_AS_UNICODE(obj);
657 Py_INCREF(obj);
658 pa->keep = obj;
659 return 0;
660#else
661 int size = PyUnicode_GET_SIZE(obj);
Thomas Heller465c8022009-02-10 18:59:04 +0000662 pa->ffi_type = &ffi_type_pointer;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000663 size += 1; /* terminating NUL */
664 size *= sizeof(wchar_t);
665 pa->value.p = PyMem_Malloc(size);
Guido van Rossum360e4b82007-05-14 22:51:27 +0000666 if (!pa->value.p) {
667 PyErr_NoMemory();
Thomas Hellerd4c93202006-03-08 19:35:11 +0000668 return -1;
Guido van Rossum360e4b82007-05-14 22:51:27 +0000669 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000670 memset(pa->value.p, 0, size);
Benjamin Petersonb173f782009-05-05 22:31:58 +0000671 pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000672 if (!pa->keep) {
673 PyMem_Free(pa->value.p);
674 return -1;
675 }
676 if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj,
677 pa->value.p, PyUnicode_GET_SIZE(obj)))
678 return -1;
679 return 0;
680#endif
681 }
682#endif
683
684 {
685 PyObject *arg;
686 arg = PyObject_GetAttrString(obj, "_as_parameter_");
687 /* Which types should we exactly allow here?
688 integers are required for using Python classes
689 as parameters (they have to expose the '_as_parameter_'
690 attribute)
691 */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000692 if (arg) {
693 int result;
694 result = ConvParam(arg, index, pa);
695 Py_DECREF(arg);
696 return result;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000697 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000698 PyErr_Format(PyExc_TypeError,
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000699 "Don't know how to convert parameter %d",
700 Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
Thomas Hellerd4c93202006-03-08 19:35:11 +0000701 return -1;
702 }
703}
704
705
Thomas Heller34596a92009-04-24 20:50:00 +0000706ffi_type *_ctypes_get_ffi_type(PyObject *obj)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000707{
708 StgDictObject *dict;
709 if (obj == NULL)
710 return &ffi_type_sint;
711 dict = PyType_stgdict(obj);
712 if (dict == NULL)
713 return &ffi_type_sint;
714#if defined(MS_WIN32) && !defined(_WIN32_WCE)
715 /* This little trick works correctly with MSVC.
716 It returns small structures in registers
717 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000718 if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
719 if (dict->ffi_type_pointer.size <= 4)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000720 return &ffi_type_sint32;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000721 else if (dict->ffi_type_pointer.size <= 8)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000722 return &ffi_type_sint64;
723 }
724#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000725 return &dict->ffi_type_pointer;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000726}
727
728
729/*
730 * libffi uses:
731 *
732 * ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi,
733 * unsigned int nargs,
734 * ffi_type *rtype,
735 * ffi_type **atypes);
736 *
737 * and then
738 *
739 * void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues);
740 */
741static int _call_function_pointer(int flags,
742 PPROC pProc,
743 void **avalues,
744 ffi_type **atypes,
745 ffi_type *restype,
746 void *resmem,
747 int argcount)
748{
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000749#ifdef WITH_THREAD
Thomas Hellerd4c93202006-03-08 19:35:11 +0000750 PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000751#endif
Thomas Heller9cac7b62008-06-06 09:31:40 +0000752 PyObject *error_object = NULL;
753 int *space;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000754 ffi_cif cif;
755 int cc;
756#ifdef MS_WIN32
757 int delta;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000758#ifndef DONT_USE_SEH
Thomas Hellerd4c93202006-03-08 19:35:11 +0000759 DWORD dwExceptionCode = 0;
760 EXCEPTION_RECORD record;
761#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000762#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +0000763 /* XXX check before here */
764 if (restype == NULL) {
765 PyErr_SetString(PyExc_RuntimeError,
766 "No ffi_type for result");
767 return -1;
768 }
769
770 cc = FFI_DEFAULT_ABI;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000771#if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000772 if ((flags & FUNCFLAG_CDECL) == 0)
773 cc = FFI_STDCALL;
774#endif
775 if (FFI_OK != ffi_prep_cif(&cif,
776 cc,
777 argcount,
778 restype,
779 atypes)) {
780 PyErr_SetString(PyExc_RuntimeError,
781 "ffi_prep_cif failed");
782 return -1;
783 }
784
Thomas Heller9cac7b62008-06-06 09:31:40 +0000785 if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
Thomas Heller34596a92009-04-24 20:50:00 +0000786 error_object = _ctypes_get_errobj(&space);
Thomas Heller9cac7b62008-06-06 09:31:40 +0000787 if (error_object == NULL)
788 return -1;
789 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000790#ifdef WITH_THREAD
Thomas Hellerd4c93202006-03-08 19:35:11 +0000791 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
792 Py_UNBLOCK_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000793#endif
Thomas Heller9cac7b62008-06-06 09:31:40 +0000794 if (flags & FUNCFLAG_USE_ERRNO) {
795 int temp = space[0];
796 space[0] = errno;
797 errno = temp;
798 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000799#ifdef MS_WIN32
Thomas Heller9cac7b62008-06-06 09:31:40 +0000800 if (flags & FUNCFLAG_USE_LASTERROR) {
801 int temp = space[1];
802 space[1] = GetLastError();
803 SetLastError(temp);
804 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000805#ifndef DONT_USE_SEH
Thomas Hellerd4c93202006-03-08 19:35:11 +0000806 __try {
807#endif
808 delta =
809#endif
810 ffi_call(&cif, (void *)pProc, resmem, avalues);
811#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000812#ifndef DONT_USE_SEH
Thomas Hellerd4c93202006-03-08 19:35:11 +0000813 }
814 __except (HandleException(GetExceptionInformation(),
815 &dwExceptionCode, &record)) {
816 ;
817 }
818#endif
Thomas Heller9cac7b62008-06-06 09:31:40 +0000819 if (flags & FUNCFLAG_USE_LASTERROR) {
820 int temp = space[1];
821 space[1] = GetLastError();
822 SetLastError(temp);
823 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000824#endif
Thomas Heller9cac7b62008-06-06 09:31:40 +0000825 if (flags & FUNCFLAG_USE_ERRNO) {
826 int temp = space[0];
827 space[0] = errno;
828 errno = temp;
829 }
830 Py_XDECREF(error_object);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000831#ifdef WITH_THREAD
Thomas Hellerd4c93202006-03-08 19:35:11 +0000832 if ((flags & FUNCFLAG_PYTHONAPI) == 0)
833 Py_BLOCK_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000834#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +0000835#ifdef MS_WIN32
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000836#ifndef DONT_USE_SEH
Thomas Hellerd4c93202006-03-08 19:35:11 +0000837 if (dwExceptionCode) {
838 SetException(dwExceptionCode, &record);
839 return -1;
840 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000841#endif
Thomas Wouters89f507f2006-12-13 04:49:30 +0000842#ifdef MS_WIN64
843 if (delta != 0) {
844 PyErr_Format(PyExc_RuntimeError,
845 "ffi_call failed with code %d",
846 delta);
847 return -1;
848 }
849#else
Thomas Hellerd4c93202006-03-08 19:35:11 +0000850 if (delta < 0) {
851 if (flags & FUNCFLAG_CDECL)
852 PyErr_Format(PyExc_ValueError,
853 "Procedure called with not enough "
854 "arguments (%d bytes missing) "
855 "or wrong calling convention",
856 -delta);
857 else
858 PyErr_Format(PyExc_ValueError,
859 "Procedure probably called with not enough "
860 "arguments (%d bytes missing)",
861 -delta);
862 return -1;
863 } else if (delta > 0) {
864 PyErr_Format(PyExc_ValueError,
865 "Procedure probably called with too many "
866 "arguments (%d bytes in excess)",
867 delta);
868 return -1;
869 }
870#endif
Thomas Wouters89f507f2006-12-13 04:49:30 +0000871#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +0000872 if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
873 return -1;
874 return 0;
875}
876
877/*
878 * Convert the C value in result into a Python object, depending on restype.
879 *
880 * - If restype is NULL, return a Python integer.
881 * - If restype is None, return None.
882 * - If restype is a simple ctypes type (c_int, c_void_p), call the type's getfunc,
883 * pass the result to checker and return the result.
884 * - If restype is another ctypes type, return an instance of that.
885 * - Otherwise, call restype and return the result.
886 */
887static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker)
888{
889 StgDictObject *dict;
890 PyObject *retval, *v;
891
892 if (restype == NULL)
Christian Heimes217cfd12007-12-02 14:31:20 +0000893 return PyLong_FromLong(*(int *)result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000894
895 if (restype == Py_None) {
896 Py_INCREF(Py_None);
897 return Py_None;
898 }
899
900 dict = PyType_stgdict(restype);
901 if (dict == NULL)
902 return PyObject_CallFunction(restype, "i", *(int *)result);
903
Thomas Heller34596a92009-04-24 20:50:00 +0000904 if (dict->getfunc && !_ctypes_simple_instance(restype)) {
Thomas Hellerd4c93202006-03-08 19:35:11 +0000905 retval = dict->getfunc(result, dict->size);
906 /* If restype is py_object (detected by comparing getfunc with
907 O_get), we have to call Py_DECREF because O_get has already
908 called Py_INCREF.
909 */
Thomas Heller34596a92009-04-24 20:50:00 +0000910 if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
Thomas Hellerd4c93202006-03-08 19:35:11 +0000911 Py_DECREF(retval);
Thomas Hellerfe8f8622006-03-14 19:53:09 +0000912 }
Thomas Hellerd4c93202006-03-08 19:35:11 +0000913 } else
Thomas Heller34596a92009-04-24 20:50:00 +0000914 retval = PyCData_FromBaseObj(restype, NULL, 0, result);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000915
916 if (!checker || !retval)
917 return retval;
918
919 v = PyObject_CallFunctionObjArgs(checker, retval, NULL);
920 if (v == NULL)
Thomas Heller34596a92009-04-24 20:50:00 +0000921 _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000922 Py_DECREF(retval);
923 return v;
924}
925
926/*
927 * Raise a new exception 'exc_class', adding additional text to the original
928 * exception string.
929 */
Thomas Heller34596a92009-04-24 20:50:00 +0000930void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...)
Thomas Hellerd4c93202006-03-08 19:35:11 +0000931{
932 va_list vargs;
933 PyObject *tp, *v, *tb, *s, *cls_str, *msg_str;
934
935 va_start(vargs, fmt);
Guido van Rossum97f9d4f2007-10-24 18:41:19 +0000936 s = PyUnicode_FromFormatV(fmt, vargs);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000937 va_end(vargs);
938 if (!s)
939 return;
940
941 PyErr_Fetch(&tp, &v, &tb);
942 PyErr_NormalizeException(&tp, &v, &tb);
943 cls_str = PyObject_Str(tp);
944 if (cls_str) {
Guido van Rossum97f9d4f2007-10-24 18:41:19 +0000945 PyUnicode_AppendAndDel(&s, cls_str);
946 PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": "));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000947 if (s == NULL)
948 goto error;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000949 } else
950 PyErr_Clear();
Thomas Heller519a0422007-11-15 20:48:54 +0000951 msg_str = PyObject_Str(v);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000952 if (msg_str)
Guido van Rossum97f9d4f2007-10-24 18:41:19 +0000953 PyUnicode_AppendAndDel(&s, msg_str);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000954 else {
955 PyErr_Clear();
Guido van Rossum97f9d4f2007-10-24 18:41:19 +0000956 PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???"));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000957 if (s == NULL)
958 goto error;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000959 }
960 PyErr_SetObject(exc_class, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000961error:
Thomas Hellerd4c93202006-03-08 19:35:11 +0000962 Py_XDECREF(tp);
963 Py_XDECREF(v);
964 Py_XDECREF(tb);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000965 Py_XDECREF(s);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000966}
967
968
969#ifdef MS_WIN32
970
971static PyObject *
972GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk)
973{
974 HRESULT hr;
975 ISupportErrorInfo *psei = NULL;
976 IErrorInfo *pei = NULL;
977 BSTR descr=NULL, helpfile=NULL, source=NULL;
978 GUID guid;
979 DWORD helpcontext=0;
980 LPOLESTR progid;
981 PyObject *obj;
Thomas Heller71fb5132008-11-26 08:45:36 +0000982 LPOLESTR text;
Thomas Hellerd4c93202006-03-08 19:35:11 +0000983
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000984 /* We absolutely have to release the GIL during COM method calls,
985 otherwise we may get a deadlock!
986 */
987#ifdef WITH_THREAD
988 Py_BEGIN_ALLOW_THREADS
989#endif
990
Thomas Hellerd4c93202006-03-08 19:35:11 +0000991 hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei);
992 if (FAILED(hr))
993 goto failed;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000994
Thomas Hellerd4c93202006-03-08 19:35:11 +0000995 hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid);
996 psei->lpVtbl->Release(psei);
Thomas Hellerd4c93202006-03-08 19:35:11 +0000997 if (FAILED(hr))
998 goto failed;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000999
Thomas Hellerd4c93202006-03-08 19:35:11 +00001000 hr = GetErrorInfo(0, &pei);
1001 if (hr != S_OK)
1002 goto failed;
1003
1004 pei->lpVtbl->GetDescription(pei, &descr);
1005 pei->lpVtbl->GetGUID(pei, &guid);
1006 pei->lpVtbl->GetHelpContext(pei, &helpcontext);
1007 pei->lpVtbl->GetHelpFile(pei, &helpfile);
1008 pei->lpVtbl->GetSource(pei, &source);
1009
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001010 pei->lpVtbl->Release(pei);
1011
Thomas Hellerd4c93202006-03-08 19:35:11 +00001012 failed:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001013#ifdef WITH_THREAD
1014 Py_END_ALLOW_THREADS
1015#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +00001016
1017 progid = NULL;
1018 ProgIDFromCLSID(&guid, &progid);
1019
Thomas Hellerd4c93202006-03-08 19:35:11 +00001020 text = FormatError(errcode);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001021 obj = Py_BuildValue(
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001022 "iu(uuuiu)",
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001023 errcode,
1024 text,
1025 descr, source, helpfile, helpcontext,
1026 progid);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001027 if (obj) {
1028 PyErr_SetObject(ComError, obj);
1029 Py_DECREF(obj);
1030 }
1031 LocalFree(text);
1032
1033 if (descr)
1034 SysFreeString(descr);
1035 if (helpfile)
1036 SysFreeString(helpfile);
1037 if (source)
1038 SysFreeString(source);
1039
1040 return NULL;
1041}
1042#endif
1043
1044/*
1045 * Requirements, must be ensured by the caller:
1046 * - argtuple is tuple of arguments
1047 * - argtypes is either NULL, or a tuple of the same size as argtuple
1048 *
1049 * - XXX various requirements for restype, not yet collected
1050 */
Thomas Heller34596a92009-04-24 20:50:00 +00001051PyObject *_ctypes_callproc(PPROC pProc,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001052 PyObject *argtuple,
1053#ifdef MS_WIN32
1054 IUnknown *pIunk,
1055 GUID *iid,
1056#endif
1057 int flags,
1058 PyObject *argtypes, /* misleading name: This is a tuple of
1059 methods, not types: the .from_param
1060 class methods of the types */
1061 PyObject *restype,
1062 PyObject *checker)
1063{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001064 Py_ssize_t i, n, argcount, argtype_count;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001065 void *resbuf;
1066 struct argument *args, *pa;
1067 ffi_type **atypes;
1068 ffi_type *rtype;
1069 void **avalues;
1070 PyObject *retval = NULL;
1071
1072 n = argcount = PyTuple_GET_SIZE(argtuple);
1073#ifdef MS_WIN32
1074 /* an optional COM object this pointer */
1075 if (pIunk)
1076 ++argcount;
1077#endif
1078
1079 args = (struct argument *)alloca(sizeof(struct argument) * argcount);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001080 if (!args) {
1081 PyErr_NoMemory();
1082 return NULL;
1083 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001084 memset(args, 0, sizeof(struct argument) * argcount);
1085 argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
1086#ifdef MS_WIN32
1087 if (pIunk) {
1088 args[0].ffi_type = &ffi_type_pointer;
1089 args[0].value.p = pIunk;
1090 pa = &args[1];
1091 } else
1092#endif
1093 pa = &args[0];
1094
1095 /* Convert the arguments */
1096 for (i = 0; i < n; ++i, ++pa) {
1097 PyObject *converter;
1098 PyObject *arg;
1099 int err;
1100
1101 arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */
1102 /* For cdecl functions, we allow more actual arguments
1103 than the length of the argtypes tuple.
Thomas Heller34596a92009-04-24 20:50:00 +00001104 This is checked in _ctypes::PyCFuncPtr_Call
Thomas Hellerd4c93202006-03-08 19:35:11 +00001105 */
1106 if (argtypes && argtype_count > i) {
1107 PyObject *v;
1108 converter = PyTuple_GET_ITEM(argtypes, i);
1109 v = PyObject_CallFunctionObjArgs(converter,
1110 arg,
1111 NULL);
1112 if (v == NULL) {
Thomas Heller34596a92009-04-24 20:50:00 +00001113 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001114 goto cleanup;
1115 }
1116
1117 err = ConvParam(v, i+1, pa);
1118 Py_DECREF(v);
1119 if (-1 == err) {
Thomas Heller34596a92009-04-24 20:50:00 +00001120 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001121 goto cleanup;
1122 }
1123 } else {
1124 err = ConvParam(arg, i+1, pa);
1125 if (-1 == err) {
Thomas Heller34596a92009-04-24 20:50:00 +00001126 _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001127 goto cleanup; /* leaking ? */
1128 }
1129 }
1130 }
1131
Thomas Heller34596a92009-04-24 20:50:00 +00001132 rtype = _ctypes_get_ffi_type(restype);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001133 resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));
1134
1135 avalues = (void **)alloca(sizeof(void *) * argcount);
1136 atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001137 if (!resbuf || !avalues || !atypes) {
1138 PyErr_NoMemory();
1139 goto cleanup;
1140 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001141 for (i = 0; i < argcount; ++i) {
1142 atypes[i] = args[i].ffi_type;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001143 if (atypes[i]->type == FFI_TYPE_STRUCT
1144#ifdef _WIN64
1145 && atypes[i]->size <= sizeof(void *)
1146#endif
1147 )
Thomas Hellerd4c93202006-03-08 19:35:11 +00001148 avalues[i] = (void *)args[i].value.p;
1149 else
1150 avalues[i] = (void *)&args[i].value;
1151 }
1152
1153 if (-1 == _call_function_pointer(flags, pProc, avalues, atypes,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001154 rtype, resbuf,
1155 Py_SAFE_DOWNCAST(argcount,
1156 Py_ssize_t,
1157 int)))
Thomas Hellerd4c93202006-03-08 19:35:11 +00001158 goto cleanup;
1159
1160#ifdef WORDS_BIGENDIAN
1161 /* libffi returns the result in a buffer with sizeof(ffi_arg). This
1162 causes problems on big endian machines, since the result buffer
1163 address cannot simply be used as result pointer, instead we must
1164 adjust the pointer value:
1165 */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001166 /*
1167 XXX I should find out and clarify why this is needed at all,
1168 especially why adjusting for ffi_type_float must be avoided on
1169 64-bit platforms.
1170 */
1171 if (rtype->type != FFI_TYPE_FLOAT
1172 && rtype->type != FFI_TYPE_STRUCT
1173 && rtype->size < sizeof(ffi_arg))
Thomas Hellerd4c93202006-03-08 19:35:11 +00001174 resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
1175#endif
1176
1177#ifdef MS_WIN32
1178 if (iid && pIunk) {
1179 if (*(int *)resbuf & 0x80000000)
1180 retval = GetComError(*(HRESULT *)resbuf, iid, pIunk);
1181 else
Christian Heimes217cfd12007-12-02 14:31:20 +00001182 retval = PyLong_FromLong(*(int *)resbuf);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001183 } else if (flags & FUNCFLAG_HRESULT) {
1184 if (*(int *)resbuf & 0x80000000)
1185 retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
1186 else
Christian Heimes217cfd12007-12-02 14:31:20 +00001187 retval = PyLong_FromLong(*(int *)resbuf);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001188 } else
1189#endif
1190 retval = GetResult(restype, resbuf, checker);
1191 cleanup:
1192 for (i = 0; i < argcount; ++i)
1193 Py_XDECREF(args[i].keep);
1194 return retval;
1195}
1196
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001197static int
1198_parse_voidp(PyObject *obj, void **address)
1199{
1200 *address = PyLong_AsVoidPtr(obj);
1201 if (*address == NULL)
1202 return 0;
1203 return 1;
1204}
1205
Thomas Hellerd4c93202006-03-08 19:35:11 +00001206#ifdef MS_WIN32
1207
Thomas Hellerd4c93202006-03-08 19:35:11 +00001208static char format_error_doc[] =
1209"FormatError([integer]) -> string\n\
1210\n\
1211Convert a win32 error code into a string. If the error code is not\n\
1212given, the return value of a call to GetLastError() is used.\n";
1213static PyObject *format_error(PyObject *self, PyObject *args)
1214{
1215 PyObject *result;
Thomas Heller71fb5132008-11-26 08:45:36 +00001216 wchar_t *lpMsgBuf;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001217 DWORD code = 0;
1218 if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
1219 return NULL;
1220 if (code == 0)
1221 code = GetLastError();
1222 lpMsgBuf = FormatError(code);
1223 if (lpMsgBuf) {
Thomas Heller71fb5132008-11-26 08:45:36 +00001224 result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf));
Thomas Hellerd4c93202006-03-08 19:35:11 +00001225 LocalFree(lpMsgBuf);
1226 } else {
Thomas Heller71fb5132008-11-26 08:45:36 +00001227 result = PyUnicode_FromString("<no description>");
Thomas Hellerd4c93202006-03-08 19:35:11 +00001228 }
1229 return result;
1230}
1231
1232static char load_library_doc[] =
1233"LoadLibrary(name) -> handle\n\
1234\n\
1235Load an executable (usually a DLL), and return a handle to it.\n\
1236The handle may be used to locate exported functions in this\n\
1237module.\n";
1238static PyObject *load_library(PyObject *self, PyObject *args)
1239{
Guido van Rossum97f9d4f2007-10-24 18:41:19 +00001240 WCHAR *name;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001241 PyObject *nameobj;
1242 PyObject *ignored;
1243 HMODULE hMod;
1244 if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
1245 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001246
Guido van Rossum97f9d4f2007-10-24 18:41:19 +00001247 name = PyUnicode_AsUnicode(nameobj);
1248 if (!name)
Thomas Hellerd4c93202006-03-08 19:35:11 +00001249 return NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001250
Guido van Rossum97f9d4f2007-10-24 18:41:19 +00001251 hMod = LoadLibraryW(name);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001252 if (!hMod)
1253 return PyErr_SetFromWindowsErr(GetLastError());
Thomas Wouters89f507f2006-12-13 04:49:30 +00001254#ifdef _WIN64
1255 return PyLong_FromVoidPtr(hMod);
1256#else
Thomas Hellerd4c93202006-03-08 19:35:11 +00001257 return Py_BuildValue("i", hMod);
Thomas Wouters89f507f2006-12-13 04:49:30 +00001258#endif
Thomas Hellerd4c93202006-03-08 19:35:11 +00001259}
1260
1261static char free_library_doc[] =
1262"FreeLibrary(handle) -> void\n\
1263\n\
1264Free the handle of an executable previously loaded by LoadLibrary.\n";
1265static PyObject *free_library(PyObject *self, PyObject *args)
1266{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001267 void *hMod;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001268 if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
Thomas Hellerd4c93202006-03-08 19:35:11 +00001269 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001270 if (!FreeLibrary((HMODULE)hMod))
Thomas Hellerd4c93202006-03-08 19:35:11 +00001271 return PyErr_SetFromWindowsErr(GetLastError());
1272 Py_INCREF(Py_None);
1273 return Py_None;
1274}
1275
1276/* obsolete, should be removed */
1277/* Only used by sample code (in samples\Windows\COM.py) */
1278static PyObject *
1279call_commethod(PyObject *self, PyObject *args)
1280{
1281 IUnknown *pIunk;
1282 int index;
1283 PyObject *arguments;
1284 PPROC *lpVtbl;
1285 PyObject *result;
1286 CDataObject *pcom;
1287 PyObject *argtypes = NULL;
1288
1289 if (!PyArg_ParseTuple(args,
1290 "OiO!|O!",
1291 &pcom, &index,
1292 &PyTuple_Type, &arguments,
1293 &PyTuple_Type, &argtypes))
1294 return NULL;
1295
1296 if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) {
1297 PyErr_Format(PyExc_TypeError,
1298 "Method takes %d arguments (%d given)",
1299 PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments));
1300 return NULL;
1301 }
1302
1303 if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) {
1304 PyErr_Format(PyExc_TypeError,
1305 "COM Pointer expected instead of %s instance",
Christian Heimes90aa7642007-12-19 02:45:37 +00001306 Py_TYPE(pcom)->tp_name);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001307 return NULL;
1308 }
1309
1310 if ((*(void **)(pcom->b_ptr)) == NULL) {
1311 PyErr_SetString(PyExc_ValueError,
1312 "The COM 'this' pointer is NULL");
1313 return NULL;
1314 }
1315
1316 pIunk = (IUnknown *)(*(void **)(pcom->b_ptr));
1317 lpVtbl = (PPROC *)(pIunk->lpVtbl);
1318
Thomas Heller34596a92009-04-24 20:50:00 +00001319 result = _ctypes_callproc(lpVtbl[index],
Thomas Hellerd4c93202006-03-08 19:35:11 +00001320 arguments,
1321#ifdef MS_WIN32
1322 pIunk,
1323 NULL,
1324#endif
1325 FUNCFLAG_HRESULT, /* flags */
1326 argtypes, /* self->argtypes */
1327 NULL, /* self->restype */
1328 NULL); /* checker */
1329 return result;
1330}
1331
1332static char copy_com_pointer_doc[] =
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001333"CopyComPointer(src, dst) -> HRESULT value\n";
Thomas Hellerd4c93202006-03-08 19:35:11 +00001334
1335static PyObject *
1336copy_com_pointer(PyObject *self, PyObject *args)
1337{
1338 PyObject *p1, *p2, *r = NULL;
1339 struct argument a, b;
1340 IUnknown *src, **pdst;
1341 if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
1342 return NULL;
1343 a.keep = b.keep = NULL;
1344
1345 if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b))
1346 goto done;
1347 src = (IUnknown *)a.value.p;
1348 pdst = (IUnknown **)b.value.p;
1349
1350 if (pdst == NULL)
Christian Heimes217cfd12007-12-02 14:31:20 +00001351 r = PyLong_FromLong(E_POINTER);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001352 else {
1353 if (src)
1354 src->lpVtbl->AddRef(src);
1355 *pdst = src;
Christian Heimes217cfd12007-12-02 14:31:20 +00001356 r = PyLong_FromLong(S_OK);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001357 }
1358 done:
1359 Py_XDECREF(a.keep);
1360 Py_XDECREF(b.keep);
1361 return r;
1362}
1363#else
1364
1365static PyObject *py_dl_open(PyObject *self, PyObject *args)
1366{
1367 char *name;
1368 void * handle;
1369#ifdef RTLD_LOCAL
1370 int mode = RTLD_NOW | RTLD_LOCAL;
1371#else
1372 /* cygwin doesn't define RTLD_LOCAL */
1373 int mode = RTLD_NOW;
1374#endif
1375 if (!PyArg_ParseTuple(args, "z|i:dlopen", &name, &mode))
1376 return NULL;
1377 mode |= RTLD_NOW;
1378 handle = ctypes_dlopen(name, mode);
1379 if (!handle) {
Thomas Heller15383a02008-07-15 19:46:52 +00001380 char *errmsg = ctypes_dlerror();
1381 if (!errmsg)
1382 errmsg = "dlopen() error";
Thomas Hellerd4c93202006-03-08 19:35:11 +00001383 PyErr_SetString(PyExc_OSError,
Thomas Heller15383a02008-07-15 19:46:52 +00001384 errmsg);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001385 return NULL;
1386 }
1387 return PyLong_FromVoidPtr(handle);
1388}
1389
1390static PyObject *py_dl_close(PyObject *self, PyObject *args)
1391{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001392 void *handle;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001393
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001394 if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
Thomas Hellerd4c93202006-03-08 19:35:11 +00001395 return NULL;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001396 if (dlclose(handle)) {
Thomas Hellerd4c93202006-03-08 19:35:11 +00001397 PyErr_SetString(PyExc_OSError,
1398 ctypes_dlerror());
1399 return NULL;
1400 }
1401 Py_INCREF(Py_None);
1402 return Py_None;
1403}
1404
1405static PyObject *py_dl_sym(PyObject *self, PyObject *args)
1406{
1407 char *name;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001408 void *handle;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001409 void *ptr;
1410
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001411 if (!PyArg_ParseTuple(args, "O&s:dlsym",
1412 &_parse_voidp, &handle, &name))
Thomas Hellerd4c93202006-03-08 19:35:11 +00001413 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001414 ptr = ctypes_dlsym((void*)handle, name);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001415 if (!ptr) {
1416 PyErr_SetString(PyExc_OSError,
1417 ctypes_dlerror());
1418 return NULL;
1419 }
Guido van Rossum360e4b82007-05-14 22:51:27 +00001420 return PyLong_FromVoidPtr(ptr);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001421}
1422#endif
1423
1424/*
1425 * Only for debugging so far: So that we can call CFunction instances
1426 *
1427 * XXX Needs to accept more arguments: flags, argtypes, restype
1428 */
1429static PyObject *
1430call_function(PyObject *self, PyObject *args)
1431{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001432 void *func;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001433 PyObject *arguments;
1434 PyObject *result;
1435
1436 if (!PyArg_ParseTuple(args,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001437 "O&O!",
1438 &_parse_voidp, &func,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001439 &PyTuple_Type, &arguments))
1440 return NULL;
1441
Thomas Heller34596a92009-04-24 20:50:00 +00001442 result = _ctypes_callproc((PPROC)func,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001443 arguments,
1444#ifdef MS_WIN32
1445 NULL,
1446 NULL,
1447#endif
1448 0, /* flags */
1449 NULL, /* self->argtypes */
1450 NULL, /* self->restype */
1451 NULL); /* checker */
1452 return result;
1453}
1454
1455/*
1456 * Only for debugging so far: So that we can call CFunction instances
1457 *
1458 * XXX Needs to accept more arguments: flags, argtypes, restype
1459 */
1460static PyObject *
1461call_cdeclfunction(PyObject *self, PyObject *args)
1462{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001463 void *func;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001464 PyObject *arguments;
1465 PyObject *result;
1466
1467 if (!PyArg_ParseTuple(args,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001468 "O&O!",
1469 &_parse_voidp, &func,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001470 &PyTuple_Type, &arguments))
1471 return NULL;
1472
Thomas Heller34596a92009-04-24 20:50:00 +00001473 result = _ctypes_callproc((PPROC)func,
Thomas Hellerd4c93202006-03-08 19:35:11 +00001474 arguments,
1475#ifdef MS_WIN32
1476 NULL,
1477 NULL,
1478#endif
1479 FUNCFLAG_CDECL, /* flags */
1480 NULL, /* self->argtypes */
1481 NULL, /* self->restype */
1482 NULL); /* checker */
1483 return result;
1484}
1485
1486/*****************************************************************
1487 * functions
1488 */
1489static char sizeof_doc[] =
1490"sizeof(C type) -> integer\n"
1491"sizeof(C instance) -> integer\n"
1492"Return the size in bytes of a C instance";
1493
1494static PyObject *
1495sizeof_func(PyObject *self, PyObject *obj)
1496{
1497 StgDictObject *dict;
1498
1499 dict = PyType_stgdict(obj);
1500 if (dict)
Christian Heimes217cfd12007-12-02 14:31:20 +00001501 return PyLong_FromSsize_t(dict->size);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001502
1503 if (CDataObject_Check(obj))
Christian Heimes217cfd12007-12-02 14:31:20 +00001504 return PyLong_FromSsize_t(((CDataObject *)obj)->b_size);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001505 PyErr_SetString(PyExc_TypeError,
1506 "this type has no size");
1507 return NULL;
1508}
1509
1510static char alignment_doc[] =
1511"alignment(C type) -> integer\n"
1512"alignment(C instance) -> integer\n"
1513"Return the alignment requirements of a C instance";
1514
1515static PyObject *
1516align_func(PyObject *self, PyObject *obj)
1517{
1518 StgDictObject *dict;
1519
1520 dict = PyType_stgdict(obj);
1521 if (dict)
Christian Heimes217cfd12007-12-02 14:31:20 +00001522 return PyLong_FromSsize_t(dict->align);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001523
1524 dict = PyObject_stgdict(obj);
1525 if (dict)
Christian Heimes217cfd12007-12-02 14:31:20 +00001526 return PyLong_FromSsize_t(dict->align);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001527
1528 PyErr_SetString(PyExc_TypeError,
1529 "no alignment info");
1530 return NULL;
1531}
1532
1533static char byref_doc[] =
Thomas Hellerc5d01262008-06-10 15:08:51 +00001534"byref(C instance[, offset=0]) -> byref-object\n"
Thomas Hellerd4c93202006-03-08 19:35:11 +00001535"Return a pointer lookalike to a C instance, only usable\n"
1536"as function argument";
1537
1538/*
1539 * We must return something which can be converted to a parameter,
1540 * but still has a reference to self.
1541 */
1542static PyObject *
Thomas Hellerc5d01262008-06-10 15:08:51 +00001543byref(PyObject *self, PyObject *args)
Thomas Hellerd4c93202006-03-08 19:35:11 +00001544{
1545 PyCArgObject *parg;
Thomas Hellerc5d01262008-06-10 15:08:51 +00001546 PyObject *obj;
1547 PyObject *pyoffset = NULL;
1548 Py_ssize_t offset = 0;
1549
1550 if (!PyArg_UnpackTuple(args, "byref", 1, 2,
1551 &obj, &pyoffset))
1552 return NULL;
1553 if (pyoffset) {
1554 offset = PyNumber_AsSsize_t(pyoffset, NULL);
1555 if (offset == -1 && PyErr_Occurred())
1556 return NULL;
1557 }
Thomas Hellerd4c93202006-03-08 19:35:11 +00001558 if (!CDataObject_Check(obj)) {
1559 PyErr_Format(PyExc_TypeError,
1560 "byref() argument must be a ctypes instance, not '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +00001561 Py_TYPE(obj)->tp_name);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001562 return NULL;
1563 }
1564
Thomas Heller34596a92009-04-24 20:50:00 +00001565 parg = PyCArgObject_new();
Thomas Hellerd4c93202006-03-08 19:35:11 +00001566 if (parg == NULL)
1567 return NULL;
1568
1569 parg->tag = 'P';
1570 parg->pffi_type = &ffi_type_pointer;
1571 Py_INCREF(obj);
1572 parg->obj = obj;
Thomas Hellerc5d01262008-06-10 15:08:51 +00001573 parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001574 return (PyObject *)parg;
1575}
1576
1577static char addressof_doc[] =
1578"addressof(C instance) -> integer\n"
1579"Return the address of the C instance internal buffer";
1580
1581static PyObject *
1582addressof(PyObject *self, PyObject *obj)
1583{
1584 if (CDataObject_Check(obj))
1585 return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
1586 PyErr_SetString(PyExc_TypeError,
1587 "invalid type");
1588 return NULL;
1589}
1590
1591static int
1592converter(PyObject *obj, void **address)
1593{
1594 *address = PyLong_AsVoidPtr(obj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001595 return *address != NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001596}
1597
1598static PyObject *
1599My_PyObj_FromPtr(PyObject *self, PyObject *args)
1600{
1601 PyObject *ob;
1602 if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob))
1603 return NULL;
1604 Py_INCREF(ob);
1605 return ob;
1606}
1607
1608static PyObject *
1609My_Py_INCREF(PyObject *self, PyObject *arg)
1610{
1611 Py_INCREF(arg); /* that's what this function is for */
1612 Py_INCREF(arg); /* that for returning it */
1613 return arg;
1614}
1615
1616static PyObject *
1617My_Py_DECREF(PyObject *self, PyObject *arg)
1618{
1619 Py_DECREF(arg); /* that's what this function is for */
1620 Py_INCREF(arg); /* that's for returning it */
1621 return arg;
1622}
1623
1624#ifdef CTYPES_UNICODE
1625
1626static char set_conversion_mode_doc[] =
1627"set_conversion_mode(encoding, errors) -> (previous-encoding, previous-errors)\n\
1628\n\
1629Set the encoding and error handling ctypes uses when converting\n\
1630between unicode and strings. Returns the previous values.\n";
1631
1632static PyObject *
1633set_conversion_mode(PyObject *self, PyObject *args)
1634{
1635 char *coding, *mode;
1636 PyObject *result;
1637
1638 if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode))
1639 return NULL;
Thomas Heller34596a92009-04-24 20:50:00 +00001640 result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001641 if (coding) {
Thomas Heller34596a92009-04-24 20:50:00 +00001642 PyMem_Free(_ctypes_conversion_encoding);
1643 _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1);
1644 strcpy(_ctypes_conversion_encoding, coding);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001645 } else {
Thomas Heller34596a92009-04-24 20:50:00 +00001646 _ctypes_conversion_encoding = NULL;
Thomas Hellerd4c93202006-03-08 19:35:11 +00001647 }
Thomas Heller34596a92009-04-24 20:50:00 +00001648 PyMem_Free(_ctypes_conversion_errors);
1649 _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1);
1650 strcpy(_ctypes_conversion_errors, mode);
Thomas Hellerd4c93202006-03-08 19:35:11 +00001651 return result;
1652}
1653#endif
1654
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001655static PyObject *
1656resize(PyObject *self, PyObject *args)
1657{
1658 CDataObject *obj;
1659 StgDictObject *dict;
1660 Py_ssize_t size;
1661
1662 if (!PyArg_ParseTuple(args,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001663 "On:resize",
Thomas Wouters89f507f2006-12-13 04:49:30 +00001664 &obj, &size))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001665 return NULL;
1666
1667 dict = PyObject_stgdict((PyObject *)obj);
1668 if (dict == NULL) {
1669 PyErr_SetString(PyExc_TypeError,
1670 "excepted ctypes instance");
1671 return NULL;
1672 }
1673 if (size < dict->size) {
1674 PyErr_Format(PyExc_ValueError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001675 "minimum size is %zd",
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001676 dict->size);
1677 return NULL;
1678 }
1679 if (obj->b_needsfree == 0) {
1680 PyErr_Format(PyExc_ValueError,
1681 "Memory cannot be resized because this object doesn't own it");
1682 return NULL;
1683 }
1684 if (size <= sizeof(obj->b_value)) {
1685 /* internal default buffer is large enough */
1686 obj->b_size = size;
1687 goto done;
1688 }
1689 if (obj->b_size <= sizeof(obj->b_value)) {
1690 /* We are currently using the objects default buffer, but it
1691 isn't large enough any more. */
1692 void *ptr = PyMem_Malloc(size);
1693 if (ptr == NULL)
1694 return PyErr_NoMemory();
1695 memset(ptr, 0, size);
1696 memmove(ptr, obj->b_ptr, obj->b_size);
1697 obj->b_ptr = ptr;
1698 obj->b_size = size;
1699 } else {
1700 void * ptr = PyMem_Realloc(obj->b_ptr, size);
1701 if (ptr == NULL)
1702 return PyErr_NoMemory();
1703 obj->b_ptr = ptr;
1704 obj->b_size = size;
1705 }
1706 done:
1707 Py_INCREF(Py_None);
1708 return Py_None;
1709}
1710
Thomas Heller13394e92008-02-13 20:40:44 +00001711static PyObject *
1712unpickle(PyObject *self, PyObject *args)
1713{
1714 PyObject *typ;
1715 PyObject *state;
1716 PyObject *result;
1717 PyObject *tmp;
1718
1719 if (!PyArg_ParseTuple(args, "OO", &typ, &state))
1720 return NULL;
1721 result = PyObject_CallMethod(typ, "__new__", "O", typ);
1722 if (result == NULL)
1723 return NULL;
1724 tmp = PyObject_CallMethod(result, "__setstate__", "O", state);
1725 if (tmp == NULL) {
1726 Py_DECREF(result);
1727 return NULL;
1728 }
1729 Py_DECREF(tmp);
1730 return result;
1731}
1732
Thomas Heller3071f812008-04-14 16:17:33 +00001733static PyObject *
1734POINTER(PyObject *self, PyObject *cls)
1735{
1736 PyObject *result;
1737 PyTypeObject *typ;
1738 PyObject *key;
1739 char *buf;
1740
Thomas Heller34596a92009-04-24 20:50:00 +00001741 result = PyDict_GetItem(_ctypes_ptrtype_cache, cls);
Thomas Heller3071f812008-04-14 16:17:33 +00001742 if (result) {
1743 Py_INCREF(result);
1744 return result;
1745 }
1746 if (PyUnicode_CheckExact(cls)) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001747 char *name = _PyUnicode_AsString(cls);
Thomas Heller3071f812008-04-14 16:17:33 +00001748 buf = alloca(strlen(name) + 3 + 1);
1749 sprintf(buf, "LP_%s", name);
Thomas Heller34596a92009-04-24 20:50:00 +00001750 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
Thomas Heller3071f812008-04-14 16:17:33 +00001751 "s(O){}",
1752 buf,
Thomas Heller34596a92009-04-24 20:50:00 +00001753 &PyCPointer_Type);
Thomas Heller3071f812008-04-14 16:17:33 +00001754 if (result == NULL)
1755 return result;
1756 key = PyLong_FromVoidPtr(result);
1757 } else if (PyType_Check(cls)) {
1758 typ = (PyTypeObject *)cls;
1759 buf = alloca(strlen(typ->tp_name) + 3 + 1);
1760 sprintf(buf, "LP_%s", typ->tp_name);
Thomas Heller34596a92009-04-24 20:50:00 +00001761 result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
Thomas Heller3071f812008-04-14 16:17:33 +00001762 "s(O){sO}",
1763 buf,
Thomas Heller34596a92009-04-24 20:50:00 +00001764 &PyCPointer_Type,
Thomas Heller3071f812008-04-14 16:17:33 +00001765 "_type_", cls);
1766 if (result == NULL)
1767 return result;
1768 Py_INCREF(cls);
1769 key = cls;
1770 } else {
1771 PyErr_SetString(PyExc_TypeError, "must be a ctypes type");
1772 return NULL;
1773 }
Thomas Heller34596a92009-04-24 20:50:00 +00001774 if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) {
Thomas Heller3071f812008-04-14 16:17:33 +00001775 Py_DECREF(result);
1776 Py_DECREF(key);
1777 return NULL;
1778 }
1779 Py_DECREF(key);
1780 return result;
1781}
1782
1783static PyObject *
1784pointer(PyObject *self, PyObject *arg)
1785{
1786 PyObject *result;
1787 PyObject *typ;
1788
Thomas Heller34596a92009-04-24 20:50:00 +00001789 typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg));
Thomas Heller3071f812008-04-14 16:17:33 +00001790 if (typ)
1791 return PyObject_CallFunctionObjArgs(typ, arg, NULL);
1792 typ = POINTER(NULL, (PyObject *)Py_TYPE(arg));
1793 if (typ == NULL)
1794 return NULL;
1795 result = PyObject_CallFunctionObjArgs(typ, arg, NULL);
1796 Py_DECREF(typ);
1797 return result;
1798}
1799
Thomas Hellerb041fda2008-04-30 17:11:46 +00001800static PyObject *
1801buffer_info(PyObject *self, PyObject *arg)
1802{
1803 StgDictObject *dict = PyType_stgdict(arg);
1804 PyObject *shape;
1805 Py_ssize_t i;
1806
1807 if (dict == NULL)
1808 dict = PyObject_stgdict(arg);
1809 if (dict == NULL) {
1810 PyErr_SetString(PyExc_TypeError,
1811 "not a ctypes type or object");
1812 return NULL;
1813 }
1814 shape = PyTuple_New(dict->ndim);
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001815 if (shape == NULL)
1816 return NULL;
Thomas Hellerb041fda2008-04-30 17:11:46 +00001817 for (i = 0; i < (int)dict->ndim; ++i)
1818 PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i]));
1819
1820 if (PyErr_Occurred()) {
1821 Py_DECREF(shape);
1822 return NULL;
1823 }
1824 return Py_BuildValue("siN", dict->format, dict->ndim, shape);
1825}
1826
Thomas Heller34596a92009-04-24 20:50:00 +00001827PyMethodDef _ctypes_module_methods[] = {
Thomas Heller9cac7b62008-06-06 09:31:40 +00001828 {"get_errno", get_errno, METH_NOARGS},
1829 {"set_errno", set_errno, METH_VARARGS},
Thomas Heller3071f812008-04-14 16:17:33 +00001830 {"POINTER", POINTER, METH_O },
1831 {"pointer", pointer, METH_O },
Thomas Heller13394e92008-02-13 20:40:44 +00001832 {"_unpickle", unpickle, METH_VARARGS },
Thomas Hellerb041fda2008-04-30 17:11:46 +00001833 {"buffer_info", buffer_info, METH_O, "Return buffer interface information"},
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001834 {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001835#ifdef CTYPES_UNICODE
1836 {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc},
1837#endif
1838#ifdef MS_WIN32
Thomas Heller9cac7b62008-06-06 09:31:40 +00001839 {"get_last_error", get_last_error, METH_NOARGS},
1840 {"set_last_error", set_last_error, METH_VARARGS},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001841 {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
1842 {"FormatError", format_error, METH_VARARGS, format_error_doc},
1843 {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
1844 {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
1845 {"call_commethod", call_commethod, METH_VARARGS },
1846 {"_check_HRESULT", check_hresult, METH_VARARGS},
1847#else
1848 {"dlopen", py_dl_open, METH_VARARGS,
1849 "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
1850 {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
1851 {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
1852#endif
1853 {"alignment", align_func, METH_O, alignment_doc},
1854 {"sizeof", sizeof_func, METH_O, sizeof_doc},
Thomas Hellerc5d01262008-06-10 15:08:51 +00001855 {"byref", byref, METH_VARARGS, byref_doc},
Thomas Hellerd4c93202006-03-08 19:35:11 +00001856 {"addressof", addressof, METH_O, addressof_doc},
1857 {"call_function", call_function, METH_VARARGS },
1858 {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
1859 {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
1860 {"Py_INCREF", My_Py_INCREF, METH_O },
1861 {"Py_DECREF", My_Py_DECREF, METH_O },
1862 {NULL, NULL} /* Sentinel */
1863};
1864
1865/*
1866 Local Variables:
1867 compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"
1868 End:
1869*/