1 /*****************************************************************
2 This file should be kept compatible with Python 2.3, see PEP 291.
3 *****************************************************************/
7 * History: First version dated from 3/97, derived from my SCMLIB version
12 * - calldll http://www.nightmare.com/software.html
13 * - libffi http://sourceware.cygnus.com/libffi/
14 * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html
15 * and, of course, Don Beaudry's MESS package, but this is more ctypes
21 How are functions called, and how are parameters converted to C ?
23 1. _ctypes.c::PyCFuncPtr_call receives an argument tuple 'inargs' and a
24 keyword dictionary 'kwds'.
26 2. After several checks, _build_callargs() is called which returns another
27 tuple 'callargs'. This may be the same tuple as 'inargs', a slice of
28 'inargs', or a completely fresh tuple, depending on several things (is is a
29 COM method, are 'paramflags' available).
31 3. _build_callargs also calculates bitarrays containing indexes into
32 the callargs tuple, specifying how to build the return value(s) of
35 4. _ctypes_callproc is then called with the 'callargs' tuple. _ctypes_callproc first
36 allocates two arrays. The first is an array of 'struct argument' items, the
37 second array has 'void *' entried.
39 5. If 'converters' are present (converters is a sequence of argtypes'
40 from_param methods), for each item in 'callargs' converter is called and the
41 result passed to ConvParam. If 'converters' are not present, each argument
42 is directly passed to ConvParm.
44 6. For each arg, ConvParam stores the contained C data (or a pointer to it,
45 for structures) into the 'struct argument' array.
47 7. Finally, a loop fills the 'void *' array so that each item points to the
48 data contained in or pointed to by the 'struct argument' array.
50 8. The 'void *' argument array is what _call_function_pointer
51 expects. _call_function_pointer then has very little to do - only some
52 libffi specific stuff, then it calls ffi_call.
54 So, there are 4 data structures holding processed arguments:
55 - the inargs tuple (in PyCFuncPtr_call)
56 - the callargs tuple (in PyCFuncPtr_call)
57 - the 'struct argguments' array
63 #include "structmember.h"
69 #include "ctypes_dlfcn.h"
79 #if defined(_DEBUG) || defined(__MINGW32__)
80 /* Don't use structured exception handling on Windows if this is defined.
81 MingW, AFAIK, doesn't support it.
87 ctypes maintains thread-local storage that has space for two error numbers:
88 private copies of the system 'errno' value and, on Windows, the system error code
89 accessed by the GetLastError() and SetLastError() api functions.
91 Foreign functions created with CDLL(..., use_errno=True), when called, swap
92 the system 'errno' value with the private copy just before the actual
93 function call, and swapped again immediately afterwards. The 'use_errno'
94 parameter defaults to False, in this case 'ctypes_errno' is not touched.
96 On Windows, foreign functions created with CDLL(..., use_last_error=True) or
97 WinDLL(..., use_last_error=True) swap the system LastError value with the
100 The values are also swapped immeditately before and after ctypes callback
101 functions are called, if the callbacks are constructed using the new
102 optional use_errno parameter set to True: CFUNCTYPE(..., use_errno=TRUE) or
103 WINFUNCTYPE(..., use_errno=True).
105 New ctypes functions are provided to access the ctypes private copies from
108 - ctypes.set_errno(value) and ctypes.set_last_error(value) store 'value' in
109 the private copy and returns the previous value.
111 - ctypes.get_errno() and ctypes.get_last_error() returns the current ctypes
112 private copies value.
116 This function creates and returns a thread-local Python object that has
117 space to store two integer error numbers; once created the Python object is
118 kept alive in the thread state dictionary as long as the thread itself.
121 _ctypes_get_errobj(int **pspace
)
123 PyObject
*dict
= PyThreadState_GetDict();
125 static PyObject
*error_object_name
;
127 PyErr_SetString(PyExc_RuntimeError
,
128 "cannot get thread state");
131 if (error_object_name
== NULL
) {
132 error_object_name
= PyString_InternFromString("ctypes.error_object");
133 if (error_object_name
== NULL
)
136 errobj
= PyDict_GetItem(dict
, error_object_name
);
140 void *space
= PyMem_Malloc(sizeof(int) * 2);
143 memset(space
, 0, sizeof(int) * 2);
144 errobj
= PyCObject_FromVoidPtr(space
, PyMem_Free
);
147 if (-1 == PyDict_SetItem(dict
, error_object_name
,
153 *pspace
= (int *)PyCObject_AsVoidPtr(errobj
);
158 get_error_internal(PyObject
*self
, PyObject
*args
, int index
)
161 PyObject
*errobj
= _ctypes_get_errobj(&space
);
166 result
= PyInt_FromLong(space
[index
]);
172 set_error_internal(PyObject
*self
, PyObject
*args
, int index
)
174 int new_errno
, old_errno
;
178 if (!PyArg_ParseTuple(args
, "i", &new_errno
))
180 errobj
= _ctypes_get_errobj(&space
);
183 old_errno
= space
[index
];
184 space
[index
] = new_errno
;
186 return PyInt_FromLong(old_errno
);
190 get_errno(PyObject
*self
, PyObject
*args
)
192 return get_error_internal(self
, args
, 0);
196 set_errno(PyObject
*self
, PyObject
*args
)
198 return set_error_internal(self
, args
, 0);
204 get_last_error(PyObject
*self
, PyObject
*args
)
206 return get_error_internal(self
, args
, 1);
210 set_last_error(PyObject
*self
, PyObject
*args
)
212 return set_error_internal(self
, args
, 1);
217 static TCHAR
*FormatError(DWORD code
)
221 n
= FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
224 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
), /* Default language */
229 while (_istspace(lpMsgBuf
[n
-1]))
231 lpMsgBuf
[n
] = _T('\0'); /* rstrip() */
237 static void SetException(DWORD code
, EXCEPTION_RECORD
*pr
)
239 /* The 'code' is a normal win32 error code so it could be handled by
240 PyErr_SetFromWindowsErr(). However, for some errors, we have additional
241 information not included in the error code. We handle those here and
242 delegate all others to the generic function. */
244 case EXCEPTION_ACCESS_VIOLATION
:
245 /* The thread attempted to read from or write
246 to a virtual address for which it does not
247 have the appropriate access. */
248 if (pr
->ExceptionInformation
[0] == 0)
249 PyErr_Format(PyExc_WindowsError
,
250 "exception: access violation reading %p",
251 pr
->ExceptionInformation
[1]);
253 PyErr_Format(PyExc_WindowsError
,
254 "exception: access violation writing %p",
255 pr
->ExceptionInformation
[1]);
258 case EXCEPTION_BREAKPOINT
:
259 /* A breakpoint was encountered. */
260 PyErr_SetString(PyExc_WindowsError
,
261 "exception: breakpoint encountered");
264 case EXCEPTION_DATATYPE_MISALIGNMENT
:
265 /* The thread attempted to read or write data that is
266 misaligned on hardware that does not provide
267 alignment. For example, 16-bit values must be
268 aligned on 2-byte boundaries, 32-bit values on
269 4-byte boundaries, and so on. */
270 PyErr_SetString(PyExc_WindowsError
,
271 "exception: datatype misalignment");
274 case EXCEPTION_SINGLE_STEP
:
275 /* A trace trap or other single-instruction mechanism
276 signaled that one instruction has been executed. */
277 PyErr_SetString(PyExc_WindowsError
,
278 "exception: single step");
281 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
282 /* The thread attempted to access an array element
283 that is out of bounds, and the underlying hardware
284 supports bounds checking. */
285 PyErr_SetString(PyExc_WindowsError
,
286 "exception: array bounds exceeded");
289 case EXCEPTION_FLT_DENORMAL_OPERAND
:
290 /* One of the operands in a floating-point operation
291 is denormal. A denormal value is one that is too
292 small to represent as a standard floating-point
294 PyErr_SetString(PyExc_WindowsError
,
295 "exception: floating-point operand denormal");
298 case EXCEPTION_FLT_DIVIDE_BY_ZERO
:
299 /* The thread attempted to divide a floating-point
300 value by a floating-point divisor of zero. */
301 PyErr_SetString(PyExc_WindowsError
,
302 "exception: float divide by zero");
305 case EXCEPTION_FLT_INEXACT_RESULT
:
306 /* The result of a floating-point operation cannot be
307 represented exactly as a decimal fraction. */
308 PyErr_SetString(PyExc_WindowsError
,
309 "exception: float inexact");
312 case EXCEPTION_FLT_INVALID_OPERATION
:
313 /* This exception represents any floating-point
314 exception not included in this list. */
315 PyErr_SetString(PyExc_WindowsError
,
316 "exception: float invalid operation");
319 case EXCEPTION_FLT_OVERFLOW
:
320 /* The exponent of a floating-point operation is
321 greater than the magnitude allowed by the
322 corresponding type. */
323 PyErr_SetString(PyExc_WindowsError
,
324 "exception: float overflow");
327 case EXCEPTION_FLT_STACK_CHECK
:
328 /* The stack overflowed or underflowed as the result
329 of a floating-point operation. */
330 PyErr_SetString(PyExc_WindowsError
,
331 "exception: stack over/underflow");
334 case EXCEPTION_STACK_OVERFLOW
:
335 /* The stack overflowed or underflowed as the result
336 of a floating-point operation. */
337 PyErr_SetString(PyExc_WindowsError
,
338 "exception: stack overflow");
341 case EXCEPTION_FLT_UNDERFLOW
:
342 /* The exponent of a floating-point operation is less
343 than the magnitude allowed by the corresponding
345 PyErr_SetString(PyExc_WindowsError
,
346 "exception: float underflow");
349 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
350 /* The thread attempted to divide an integer value by
351 an integer divisor of zero. */
352 PyErr_SetString(PyExc_WindowsError
,
353 "exception: integer divide by zero");
356 case EXCEPTION_INT_OVERFLOW
:
357 /* The result of an integer operation caused a carry
358 out of the most significant bit of the result. */
359 PyErr_SetString(PyExc_WindowsError
,
360 "exception: integer overflow");
363 case EXCEPTION_PRIV_INSTRUCTION
:
364 /* The thread attempted to execute an instruction
365 whose operation is not allowed in the current
367 PyErr_SetString(PyExc_WindowsError
,
368 "exception: priviledged instruction");
371 case EXCEPTION_NONCONTINUABLE_EXCEPTION
:
372 /* The thread attempted to continue execution after a
373 noncontinuable exception occurred. */
374 PyErr_SetString(PyExc_WindowsError
,
375 "exception: nocontinuable");
379 PyErr_SetFromWindowsErr(code
);
384 static DWORD
HandleException(EXCEPTION_POINTERS
*ptrs
,
385 DWORD
*pdw
, EXCEPTION_RECORD
*record
)
387 *pdw
= ptrs
->ExceptionRecord
->ExceptionCode
;
388 *record
= *ptrs
->ExceptionRecord
;
389 return EXCEPTION_EXECUTE_HANDLER
;
394 check_hresult(PyObject
*self
, PyObject
*args
)
397 if (!PyArg_ParseTuple(args
, "i", &hr
))
400 return PyErr_SetFromWindowsErr(hr
);
401 return PyInt_FromLong(hr
);
406 /**************************************************************/
409 PyCArgObject_new(void)
412 p
= PyObject_New(PyCArgObject
, &PyCArg_Type
);
418 memset(&p
->value
, 0, sizeof(p
->value
));
423 PyCArg_dealloc(PyCArgObject
*self
)
425 Py_XDECREF(self
->obj
);
430 PyCArg_repr(PyCArgObject
*self
)
436 sprintf(buffer
, "<cparam '%c' (%d)>",
437 self
->tag
, self
->value
.b
);
441 sprintf(buffer
, "<cparam '%c' (%d)>",
442 self
->tag
, self
->value
.h
);
446 sprintf(buffer
, "<cparam '%c' (%d)>",
447 self
->tag
, self
->value
.i
);
451 sprintf(buffer
, "<cparam '%c' (%ld)>",
452 self
->tag
, self
->value
.l
);
455 #ifdef HAVE_LONG_LONG
460 "<cparam '%c' (%I64d)>",
462 "<cparam '%c' (%qd)>",
464 self
->tag
, self
->value
.q
);
468 sprintf(buffer
, "<cparam '%c' (%f)>",
469 self
->tag
, self
->value
.d
);
472 sprintf(buffer
, "<cparam '%c' (%f)>",
473 self
->tag
, self
->value
.f
);
477 sprintf(buffer
, "<cparam '%c' (%c)>",
478 self
->tag
, self
->value
.c
);
481 /* Hm, are these 'z' and 'Z' codes useful at all?
482 Shouldn't they be replaced by the functionality of c_string
488 sprintf(buffer
, "<cparam '%c' (%p)>",
489 self
->tag
, self
->value
.p
);
493 sprintf(buffer
, "<cparam '%c' at %p>",
497 return PyString_FromString(buffer
);
500 static PyMemberDef PyCArgType_members
[] = {
502 offsetof(PyCArgObject
, obj
), READONLY
,
503 "the wrapped object" },
507 PyTypeObject PyCArg_Type
= {
508 PyVarObject_HEAD_INIT(NULL
, 0)
510 sizeof(PyCArgObject
),
512 (destructor
)PyCArg_dealloc
, /* tp_dealloc */
517 (reprfunc
)PyCArg_repr
, /* tp_repr */
518 0, /* tp_as_number */
519 0, /* tp_as_sequence */
520 0, /* tp_as_mapping */
526 0, /* tp_as_buffer */
527 Py_TPFLAGS_DEFAULT
, /* tp_flags */
531 0, /* tp_richcompare */
532 0, /* tp_weaklistoffset */
536 PyCArgType_members
, /* tp_members */
539 /****************************************************************/
541 * Convert a PyObject * into a parameter suitable to pass to an
544 * 1. Python integers are converted to C int and passed by value.
545 * Py_None is converted to a C NULL pointer.
547 * 2. 3-tuples are expected to have a format character in the first
548 * item, which must be 'i', 'f', 'd', 'q', or 'P'.
549 * The second item will have to be an integer, float, double, long long
550 * or integer (denoting an address void *), will be converted to the
551 * corresponding C data type and passed by value.
553 * 3. Other Python objects are tested for an '_as_parameter_' attribute.
554 * The value of this attribute must be an integer which will be passed
555 * by value, or a 2-tuple or 3-tuple which will be used according
556 * to point 2 above. The third item (if any), is ignored. It is normally
557 * used to keep the object alive where this parameter refers to.
558 * XXX This convention is dangerous - you can construct arbitrary tuples
559 * in Python and pass them. Would it be safer to use a custom container
560 * datatype instead of a tuple?
562 * 4. Other Python objects cannot be passed as parameters - an exception is raised.
564 * 5. ConvParam will store the converted result in a struct containing format
574 #ifdef HAVE_LONG_LONG
590 * Convert a single Python object into a PyCArgObject and return it.
592 static int ConvParam(PyObject
*obj
, Py_ssize_t index
, struct argument
*pa
)
595 pa
->keep
= NULL
; /* so we cannot forget it later */
597 dict
= PyObject_stgdict(obj
);
600 assert(dict
->paramfunc
);
601 /* If it has an stgdict, it is a CDataObject */
602 carg
= dict
->paramfunc((CDataObject
*)obj
);
603 pa
->ffi_type
= carg
->pffi_type
;
604 memcpy(&pa
->value
, &carg
->value
, sizeof(pa
->value
));
605 pa
->keep
= (PyObject
*)carg
;
609 if (PyCArg_CheckExact(obj
)) {
610 PyCArgObject
*carg
= (PyCArgObject
*)obj
;
611 pa
->ffi_type
= carg
->pffi_type
;
614 memcpy(&pa
->value
, &carg
->value
, sizeof(pa
->value
));
618 /* check for None, integer, string or unicode and use directly if successful */
619 if (obj
== Py_None
) {
620 pa
->ffi_type
= &ffi_type_pointer
;
625 if (PyInt_Check(obj
)) {
626 pa
->ffi_type
= &ffi_type_sint
;
627 pa
->value
.i
= PyInt_AS_LONG(obj
);
631 if (PyLong_Check(obj
)) {
632 pa
->ffi_type
= &ffi_type_sint
;
633 pa
->value
.i
= (long)PyLong_AsUnsignedLong(obj
);
634 if (pa
->value
.i
== -1 && PyErr_Occurred()) {
636 pa
->value
.i
= PyLong_AsLong(obj
);
637 if (pa
->value
.i
== -1 && PyErr_Occurred()) {
638 PyErr_SetString(PyExc_OverflowError
,
639 "long int too long to convert");
646 if (PyString_Check(obj
)) {
647 pa
->ffi_type
= &ffi_type_pointer
;
648 pa
->value
.p
= PyString_AS_STRING(obj
);
654 #ifdef CTYPES_UNICODE
655 if (PyUnicode_Check(obj
)) {
656 #ifdef HAVE_USABLE_WCHAR_T
657 pa
->ffi_type
= &ffi_type_pointer
;
658 pa
->value
.p
= PyUnicode_AS_UNICODE(obj
);
663 int size
= PyUnicode_GET_SIZE(obj
);
664 pa
->ffi_type
= &ffi_type_pointer
;
665 size
+= 1; /* terminating NUL */
666 size
*= sizeof(wchar_t);
667 pa
->value
.p
= PyMem_Malloc(size
);
672 memset(pa
->value
.p
, 0, size
);
673 pa
->keep
= PyCObject_FromVoidPtr(pa
->value
.p
, PyMem_Free
);
675 PyMem_Free(pa
->value
.p
);
678 if (-1 == PyUnicode_AsWideChar((PyUnicodeObject
*)obj
,
679 pa
->value
.p
, PyUnicode_GET_SIZE(obj
)))
688 arg
= PyObject_GetAttrString(obj
, "_as_parameter_");
689 /* Which types should we exactly allow here?
690 integers are required for using Python classes
691 as parameters (they have to expose the '_as_parameter_'
696 result
= ConvParam(arg
, index
, pa
);
700 PyErr_Format(PyExc_TypeError
,
701 "Don't know how to convert parameter %d",
702 Py_SAFE_DOWNCAST(index
, Py_ssize_t
, int));
708 ffi_type
*_ctypes_get_ffi_type(PyObject
*obj
)
712 return &ffi_type_sint
;
713 dict
= PyType_stgdict(obj
);
715 return &ffi_type_sint
;
716 #if defined(MS_WIN32) && !defined(_WIN32_WCE)
717 /* This little trick works correctly with MSVC.
718 It returns small structures in registers
720 if (dict
->ffi_type_pointer
.type
== FFI_TYPE_STRUCT
) {
721 if (dict
->ffi_type_pointer
.size
<= 4)
722 return &ffi_type_sint32
;
723 else if (dict
->ffi_type_pointer
.size
<= 8)
724 return &ffi_type_sint64
;
727 return &dict
->ffi_type_pointer
;
734 * ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi,
735 * unsigned int nargs,
737 * ffi_type **atypes);
741 * void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues);
743 static int _call_function_pointer(int flags
,
752 PyThreadState
*_save
= NULL
; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
754 PyObject
*error_object
= NULL
;
761 DWORD dwExceptionCode
= 0;
762 EXCEPTION_RECORD record
;
765 /* XXX check before here */
766 if (restype
== NULL
) {
767 PyErr_SetString(PyExc_RuntimeError
,
768 "No ffi_type for result");
772 cc
= FFI_DEFAULT_ABI
;
773 #if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE)
774 if ((flags
& FUNCFLAG_CDECL
) == 0)
777 if (FFI_OK
!= ffi_prep_cif(&cif
,
782 PyErr_SetString(PyExc_RuntimeError
,
783 "ffi_prep_cif failed");
787 if (flags
& (FUNCFLAG_USE_ERRNO
| FUNCFLAG_USE_LASTERROR
)) {
788 error_object
= _ctypes_get_errobj(&space
);
789 if (error_object
== NULL
)
793 if ((flags
& FUNCFLAG_PYTHONAPI
) == 0)
796 if (flags
& FUNCFLAG_USE_ERRNO
) {
802 if (flags
& FUNCFLAG_USE_LASTERROR
) {
804 space
[1] = GetLastError();
812 ffi_call(&cif
, (void *)pProc
, resmem
, avalues
);
816 __except (HandleException(GetExceptionInformation(),
817 &dwExceptionCode
, &record
)) {
821 if (flags
& FUNCFLAG_USE_LASTERROR
) {
823 space
[1] = GetLastError();
827 if (flags
& FUNCFLAG_USE_ERRNO
) {
832 Py_XDECREF(error_object
);
834 if ((flags
& FUNCFLAG_PYTHONAPI
) == 0)
839 if (dwExceptionCode
) {
840 SetException(dwExceptionCode
, &record
);
846 PyErr_Format(PyExc_RuntimeError
,
847 "ffi_call failed with code %d",
853 if (flags
& FUNCFLAG_CDECL
)
854 PyErr_Format(PyExc_ValueError
,
855 "Procedure called with not enough "
856 "arguments (%d bytes missing) "
857 "or wrong calling convention",
860 PyErr_Format(PyExc_ValueError
,
861 "Procedure probably called with not enough "
862 "arguments (%d bytes missing)",
865 } else if (delta
> 0) {
866 PyErr_Format(PyExc_ValueError
,
867 "Procedure probably called with too many "
868 "arguments (%d bytes in excess)",
874 if ((flags
& FUNCFLAG_PYTHONAPI
) && PyErr_Occurred())
880 * Convert the C value in result into a Python object, depending on restype.
882 * - If restype is NULL, return a Python integer.
883 * - If restype is None, return None.
884 * - If restype is a simple ctypes type (c_int, c_void_p), call the type's getfunc,
885 * pass the result to checker and return the result.
886 * - If restype is another ctypes type, return an instance of that.
887 * - Otherwise, call restype and return the result.
889 static PyObject
*GetResult(PyObject
*restype
, void *result
, PyObject
*checker
)
892 PyObject
*retval
, *v
;
895 return PyInt_FromLong(*(int *)result
);
897 if (restype
== Py_None
) {
902 dict
= PyType_stgdict(restype
);
904 return PyObject_CallFunction(restype
, "i", *(int *)result
);
906 if (dict
->getfunc
&& !_ctypes_simple_instance(restype
)) {
907 retval
= dict
->getfunc(result
, dict
->size
);
908 /* If restype is py_object (detected by comparing getfunc with
909 O_get), we have to call Py_DECREF because O_get has already
912 if (dict
->getfunc
== _ctypes_get_fielddesc("O")->getfunc
) {
916 retval
= PyCData_FromBaseObj(restype
, NULL
, 0, result
);
918 if (!checker
|| !retval
)
921 v
= PyObject_CallFunctionObjArgs(checker
, retval
, NULL
);
923 _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__
-2);
929 * Raise a new exception 'exc_class', adding additional text to the original
932 void _ctypes_extend_error(PyObject
*exc_class
, char *fmt
, ...)
935 PyObject
*tp
, *v
, *tb
, *s
, *cls_str
, *msg_str
;
937 va_start(vargs
, fmt
);
938 s
= PyString_FromFormatV(fmt
, vargs
);
943 PyErr_Fetch(&tp
, &v
, &tb
);
944 PyErr_NormalizeException(&tp
, &v
, &tb
);
945 cls_str
= PyObject_Str(tp
);
947 PyString_ConcatAndDel(&s
, cls_str
);
948 PyString_ConcatAndDel(&s
, PyString_FromString(": "));
953 msg_str
= PyObject_Str(v
);
955 PyString_ConcatAndDel(&s
, msg_str
);
958 PyString_ConcatAndDel(&s
, PyString_FromString("???"));
962 PyErr_SetObject(exc_class
, s
);
974 GetComError(HRESULT errcode
, GUID
*riid
, IUnknown
*pIunk
)
977 ISupportErrorInfo
*psei
= NULL
;
978 IErrorInfo
*pei
= NULL
;
979 BSTR descr
=NULL
, helpfile
=NULL
, source
=NULL
;
986 /* We absolutely have to release the GIL during COM method calls,
987 otherwise we may get a deadlock!
990 Py_BEGIN_ALLOW_THREADS
993 hr
= pIunk
->lpVtbl
->QueryInterface(pIunk
, &IID_ISupportErrorInfo
, (void **)&psei
);
997 hr
= psei
->lpVtbl
->InterfaceSupportsErrorInfo(psei
, riid
);
998 psei
->lpVtbl
->Release(psei
);
1002 hr
= GetErrorInfo(0, &pei
);
1006 pei
->lpVtbl
->GetDescription(pei
, &descr
);
1007 pei
->lpVtbl
->GetGUID(pei
, &guid
);
1008 pei
->lpVtbl
->GetHelpContext(pei
, &helpcontext
);
1009 pei
->lpVtbl
->GetHelpFile(pei
, &helpfile
);
1010 pei
->lpVtbl
->GetSource(pei
, &source
);
1012 pei
->lpVtbl
->Release(pei
);
1016 Py_END_ALLOW_THREADS
1020 ProgIDFromCLSID(&guid
, &progid
);
1022 text
= FormatError(errcode
);
1023 obj
= Py_BuildValue(
1031 descr
, source
, helpfile
, helpcontext
,
1034 PyErr_SetObject(ComError
, obj
);
1040 SysFreeString(descr
);
1042 SysFreeString(helpfile
);
1044 SysFreeString(source
);
1051 * Requirements, must be ensured by the caller:
1052 * - argtuple is tuple of arguments
1053 * - argtypes is either NULL, or a tuple of the same size as argtuple
1055 * - XXX various requirements for restype, not yet collected
1057 PyObject
*_ctypes_callproc(PPROC pProc
,
1064 PyObject
*argtypes
, /* misleading name: This is a tuple of
1065 methods, not types: the .from_param
1066 class methods of the types */
1070 Py_ssize_t i
, n
, argcount
, argtype_count
;
1072 struct argument
*args
, *pa
;
1076 PyObject
*retval
= NULL
;
1078 n
= argcount
= PyTuple_GET_SIZE(argtuple
);
1080 /* an optional COM object this pointer */
1085 args
= (struct argument
*)alloca(sizeof(struct argument
) * argcount
);
1090 memset(args
, 0, sizeof(struct argument
) * argcount
);
1091 argtype_count
= argtypes
? PyTuple_GET_SIZE(argtypes
) : 0;
1094 args
[0].ffi_type
= &ffi_type_pointer
;
1095 args
[0].value
.p
= pIunk
;
1101 /* Convert the arguments */
1102 for (i
= 0; i
< n
; ++i
, ++pa
) {
1103 PyObject
*converter
;
1107 arg
= PyTuple_GET_ITEM(argtuple
, i
); /* borrowed ref */
1108 /* For cdecl functions, we allow more actual arguments
1109 than the length of the argtypes tuple.
1110 This is checked in _ctypes::PyCFuncPtr_Call
1112 if (argtypes
&& argtype_count
> i
) {
1114 converter
= PyTuple_GET_ITEM(argtypes
, i
);
1115 v
= PyObject_CallFunctionObjArgs(converter
,
1119 _ctypes_extend_error(PyExc_ArgError
, "argument %d: ", i
+1);
1123 err
= ConvParam(v
, i
+1, pa
);
1126 _ctypes_extend_error(PyExc_ArgError
, "argument %d: ", i
+1);
1130 err
= ConvParam(arg
, i
+1, pa
);
1132 _ctypes_extend_error(PyExc_ArgError
, "argument %d: ", i
+1);
1133 goto cleanup
; /* leaking ? */
1138 rtype
= _ctypes_get_ffi_type(restype
);
1139 resbuf
= alloca(max(rtype
->size
, sizeof(ffi_arg
)));
1141 avalues
= (void **)alloca(sizeof(void *) * argcount
);
1142 atypes
= (ffi_type
**)alloca(sizeof(ffi_type
*) * argcount
);
1143 if (!resbuf
|| !avalues
|| !atypes
) {
1147 for (i
= 0; i
< argcount
; ++i
) {
1148 atypes
[i
] = args
[i
].ffi_type
;
1149 if (atypes
[i
]->type
== FFI_TYPE_STRUCT
1151 && atypes
[i
]->size
<= sizeof(void *)
1154 avalues
[i
] = (void *)args
[i
].value
.p
;
1156 avalues
[i
] = (void *)&args
[i
].value
;
1159 if (-1 == _call_function_pointer(flags
, pProc
, avalues
, atypes
,
1161 Py_SAFE_DOWNCAST(argcount
,
1166 #ifdef WORDS_BIGENDIAN
1167 /* libffi returns the result in a buffer with sizeof(ffi_arg). This
1168 causes problems on big endian machines, since the result buffer
1169 address cannot simply be used as result pointer, instead we must
1170 adjust the pointer value:
1173 XXX I should find out and clarify why this is needed at all,
1174 especially why adjusting for ffi_type_float must be avoided on
1177 if (rtype
->type
!= FFI_TYPE_FLOAT
1178 && rtype
->type
!= FFI_TYPE_STRUCT
1179 && rtype
->size
< sizeof(ffi_arg
))
1180 resbuf
= (char *)resbuf
+ sizeof(ffi_arg
) - rtype
->size
;
1185 if (*(int *)resbuf
& 0x80000000)
1186 retval
= GetComError(*(HRESULT
*)resbuf
, iid
, pIunk
);
1188 retval
= PyInt_FromLong(*(int *)resbuf
);
1189 } else if (flags
& FUNCFLAG_HRESULT
) {
1190 if (*(int *)resbuf
& 0x80000000)
1191 retval
= PyErr_SetFromWindowsErr(*(int *)resbuf
);
1193 retval
= PyInt_FromLong(*(int *)resbuf
);
1196 retval
= GetResult(restype
, resbuf
, checker
);
1198 for (i
= 0; i
< argcount
; ++i
)
1199 Py_XDECREF(args
[i
].keep
);
1204 _parse_voidp(PyObject
*obj
, void **address
)
1206 *address
= PyLong_AsVoidPtr(obj
);
1207 if (*address
== NULL
)
1215 # define PYBUILD_TSTR "u"
1217 # define PYBUILD_TSTR "s"
1219 # define _T(text) text
1223 static char format_error_doc
[] =
1224 "FormatError([integer]) -> string\n\
1226 Convert a win32 error code into a string. If the error code is not\n\
1227 given, the return value of a call to GetLastError() is used.\n";
1228 static PyObject
*format_error(PyObject
*self
, PyObject
*args
)
1233 if (!PyArg_ParseTuple(args
, "|i:FormatError", &code
))
1236 code
= GetLastError();
1237 lpMsgBuf
= FormatError(code
);
1239 result
= Py_BuildValue(PYBUILD_TSTR
, lpMsgBuf
);
1240 LocalFree(lpMsgBuf
);
1242 result
= Py_BuildValue("s", "<no description>");
1247 static char load_library_doc
[] =
1248 "LoadLibrary(name) -> handle\n\
1250 Load an executable (usually a DLL), and return a handle to it.\n\
1251 The handle may be used to locate exported functions in this\n\
1253 static PyObject
*load_library(PyObject
*self
, PyObject
*args
)
1259 if (!PyArg_ParseTuple(args
, "O|O:LoadLibrary", &nameobj
, &ignored
))
1262 name
= alloca((PyString_Size(nameobj
) + 1) * sizeof(WCHAR
));
1270 char *aname
= PyString_AsString(nameobj
);
1273 r
= MultiByteToWideChar(CP_ACP
, 0, aname
, -1, name
, PyString_Size(nameobj
) + 1);
1277 name
= PyString_AsString(nameobj
);
1282 hMod
= LoadLibrary(name
);
1284 return PyErr_SetFromWindowsErr(GetLastError());
1286 return PyLong_FromVoidPtr(hMod
);
1288 return Py_BuildValue("i", hMod
);
1292 static char free_library_doc
[] =
1293 "FreeLibrary(handle) -> void\n\
1295 Free the handle of an executable previously loaded by LoadLibrary.\n";
1296 static PyObject
*free_library(PyObject
*self
, PyObject
*args
)
1299 if (!PyArg_ParseTuple(args
, "O&:FreeLibrary", &_parse_voidp
, &hMod
))
1301 if (!FreeLibrary((HMODULE
)hMod
))
1302 return PyErr_SetFromWindowsErr(GetLastError());
1307 /* obsolete, should be removed */
1308 /* Only used by sample code (in samples\Windows\COM.py) */
1310 call_commethod(PyObject
*self
, PyObject
*args
)
1314 PyObject
*arguments
;
1318 PyObject
*argtypes
= NULL
;
1320 if (!PyArg_ParseTuple(args
,
1323 &PyTuple_Type
, &arguments
,
1324 &PyTuple_Type
, &argtypes
))
1327 if (argtypes
&& (PyTuple_GET_SIZE(arguments
) != PyTuple_GET_SIZE(argtypes
))) {
1328 PyErr_Format(PyExc_TypeError
,
1329 "Method takes %d arguments (%d given)",
1330 PyTuple_GET_SIZE(argtypes
), PyTuple_GET_SIZE(arguments
));
1334 if (!CDataObject_Check(pcom
) || (pcom
->b_size
!= sizeof(void *))) {
1335 PyErr_Format(PyExc_TypeError
,
1336 "COM Pointer expected instead of %s instance",
1337 Py_TYPE(pcom
)->tp_name
);
1341 if ((*(void **)(pcom
->b_ptr
)) == NULL
) {
1342 PyErr_SetString(PyExc_ValueError
,
1343 "The COM 'this' pointer is NULL");
1347 pIunk
= (IUnknown
*)(*(void **)(pcom
->b_ptr
));
1348 lpVtbl
= (PPROC
*)(pIunk
->lpVtbl
);
1350 result
= _ctypes_callproc(lpVtbl
[index
],
1356 FUNCFLAG_HRESULT
, /* flags */
1357 argtypes
, /* self->argtypes */
1358 NULL
, /* self->restype */
1359 NULL
); /* checker */
1363 static char copy_com_pointer_doc
[] =
1364 "CopyComPointer(src, dst) -> HRESULT value\n";
1367 copy_com_pointer(PyObject
*self
, PyObject
*args
)
1369 PyObject
*p1
, *p2
, *r
= NULL
;
1370 struct argument a
, b
;
1371 IUnknown
*src
, **pdst
;
1372 if (!PyArg_ParseTuple(args
, "OO:CopyComPointer", &p1
, &p2
))
1374 a
.keep
= b
.keep
= NULL
;
1376 if (-1 == ConvParam(p1
, 0, &a
) || -1 == ConvParam(p2
, 1, &b
))
1378 src
= (IUnknown
*)a
.value
.p
;
1379 pdst
= (IUnknown
**)b
.value
.p
;
1382 r
= PyInt_FromLong(E_POINTER
);
1385 src
->lpVtbl
->AddRef(src
);
1387 r
= PyInt_FromLong(S_OK
);
1396 static PyObject
*py_dl_open(PyObject
*self
, PyObject
*args
)
1401 int mode
= RTLD_NOW
| RTLD_LOCAL
;
1403 /* cygwin doesn't define RTLD_LOCAL */
1404 int mode
= RTLD_NOW
;
1406 if (!PyArg_ParseTuple(args
, "z|i:dlopen", &name
, &mode
))
1409 handle
= ctypes_dlopen(name
, mode
);
1411 char *errmsg
= ctypes_dlerror();
1413 errmsg
= "dlopen() error";
1414 PyErr_SetString(PyExc_OSError
,
1418 return PyLong_FromVoidPtr(handle
);
1421 static PyObject
*py_dl_close(PyObject
*self
, PyObject
*args
)
1425 if (!PyArg_ParseTuple(args
, "O&:dlclose", &_parse_voidp
, &handle
))
1427 if (dlclose(handle
)) {
1428 PyErr_SetString(PyExc_OSError
,
1436 static PyObject
*py_dl_sym(PyObject
*self
, PyObject
*args
)
1442 if (!PyArg_ParseTuple(args
, "O&s:dlsym",
1443 &_parse_voidp
, &handle
, &name
))
1445 ptr
= ctypes_dlsym((void*)handle
, name
);
1447 PyErr_SetString(PyExc_OSError
,
1451 return PyLong_FromVoidPtr(ptr
);
1456 * Only for debugging so far: So that we can call CFunction instances
1458 * XXX Needs to accept more arguments: flags, argtypes, restype
1461 call_function(PyObject
*self
, PyObject
*args
)
1464 PyObject
*arguments
;
1467 if (!PyArg_ParseTuple(args
,
1469 &_parse_voidp
, &func
,
1470 &PyTuple_Type
, &arguments
))
1473 result
= _ctypes_callproc((PPROC
)func
,
1480 NULL
, /* self->argtypes */
1481 NULL
, /* self->restype */
1482 NULL
); /* checker */
1487 * Only for debugging so far: So that we can call CFunction instances
1489 * XXX Needs to accept more arguments: flags, argtypes, restype
1492 call_cdeclfunction(PyObject
*self
, PyObject
*args
)
1495 PyObject
*arguments
;
1498 if (!PyArg_ParseTuple(args
,
1500 &_parse_voidp
, &func
,
1501 &PyTuple_Type
, &arguments
))
1504 result
= _ctypes_callproc((PPROC
)func
,
1510 FUNCFLAG_CDECL
, /* flags */
1511 NULL
, /* self->argtypes */
1512 NULL
, /* self->restype */
1513 NULL
); /* checker */
1517 /*****************************************************************
1520 static char sizeof_doc
[] =
1521 "sizeof(C type) -> integer\n"
1522 "sizeof(C instance) -> integer\n"
1523 "Return the size in bytes of a C instance";
1526 sizeof_func(PyObject
*self
, PyObject
*obj
)
1528 StgDictObject
*dict
;
1530 dict
= PyType_stgdict(obj
);
1532 return PyInt_FromSsize_t(dict
->size
);
1534 if (CDataObject_Check(obj
))
1535 return PyInt_FromSsize_t(((CDataObject
*)obj
)->b_size
);
1536 PyErr_SetString(PyExc_TypeError
,
1537 "this type has no size");
1541 static char alignment_doc
[] =
1542 "alignment(C type) -> integer\n"
1543 "alignment(C instance) -> integer\n"
1544 "Return the alignment requirements of a C instance";
1547 align_func(PyObject
*self
, PyObject
*obj
)
1549 StgDictObject
*dict
;
1551 dict
= PyType_stgdict(obj
);
1553 return PyInt_FromSsize_t(dict
->align
);
1555 dict
= PyObject_stgdict(obj
);
1557 return PyInt_FromSsize_t(dict
->align
);
1559 PyErr_SetString(PyExc_TypeError
,
1560 "no alignment info");
1564 static char byref_doc
[] =
1565 "byref(C instance[, offset=0]) -> byref-object\n"
1566 "Return a pointer lookalike to a C instance, only usable\n"
1567 "as function argument";
1570 * We must return something which can be converted to a parameter,
1571 * but still has a reference to self.
1574 byref(PyObject
*self
, PyObject
*args
)
1578 PyObject
*pyoffset
= NULL
;
1579 Py_ssize_t offset
= 0;
1581 if (!PyArg_UnpackTuple(args
, "byref", 1, 2,
1585 offset
= PyNumber_AsSsize_t(pyoffset
, NULL
);
1586 if (offset
== -1 && PyErr_Occurred())
1589 if (!CDataObject_Check(obj
)) {
1590 PyErr_Format(PyExc_TypeError
,
1591 "byref() argument must be a ctypes instance, not '%s'",
1592 Py_TYPE(obj
)->tp_name
);
1596 parg
= PyCArgObject_new();
1601 parg
->pffi_type
= &ffi_type_pointer
;
1604 parg
->value
.p
= (char *)((CDataObject
*)obj
)->b_ptr
+ offset
;
1605 return (PyObject
*)parg
;
1608 static char addressof_doc
[] =
1609 "addressof(C instance) -> integer\n"
1610 "Return the address of the C instance internal buffer";
1613 addressof(PyObject
*self
, PyObject
*obj
)
1615 if (CDataObject_Check(obj
))
1616 return PyLong_FromVoidPtr(((CDataObject
*)obj
)->b_ptr
);
1617 PyErr_SetString(PyExc_TypeError
,
1623 converter(PyObject
*obj
, void **address
)
1625 *address
= PyLong_AsVoidPtr(obj
);
1626 return *address
!= NULL
;
1630 My_PyObj_FromPtr(PyObject
*self
, PyObject
*args
)
1633 if (!PyArg_ParseTuple(args
, "O&:PyObj_FromPtr", converter
, &ob
))
1640 My_Py_INCREF(PyObject
*self
, PyObject
*arg
)
1642 Py_INCREF(arg
); /* that's what this function is for */
1643 Py_INCREF(arg
); /* that for returning it */
1648 My_Py_DECREF(PyObject
*self
, PyObject
*arg
)
1650 Py_DECREF(arg
); /* that's what this function is for */
1651 Py_INCREF(arg
); /* that's for returning it */
1655 #ifdef CTYPES_UNICODE
1657 static char set_conversion_mode_doc
[] =
1658 "set_conversion_mode(encoding, errors) -> (previous-encoding, previous-errors)\n\
1660 Set the encoding and error handling ctypes uses when converting\n\
1661 between unicode and strings. Returns the previous values.\n";
1664 set_conversion_mode(PyObject
*self
, PyObject
*args
)
1666 char *coding
, *mode
;
1669 if (!PyArg_ParseTuple(args
, "zs:set_conversion_mode", &coding
, &mode
))
1671 result
= Py_BuildValue("(zz)", _ctypes_conversion_encoding
, _ctypes_conversion_errors
);
1673 PyMem_Free(_ctypes_conversion_encoding
);
1674 _ctypes_conversion_encoding
= PyMem_Malloc(strlen(coding
) + 1);
1675 strcpy(_ctypes_conversion_encoding
, coding
);
1677 _ctypes_conversion_encoding
= NULL
;
1679 PyMem_Free(_ctypes_conversion_errors
);
1680 _ctypes_conversion_errors
= PyMem_Malloc(strlen(mode
) + 1);
1681 strcpy(_ctypes_conversion_errors
, mode
);
1687 resize(PyObject
*self
, PyObject
*args
)
1690 StgDictObject
*dict
;
1693 if (!PyArg_ParseTuple(args
,
1694 #if (PY_VERSION_HEX < 0x02050000)
1702 dict
= PyObject_stgdict((PyObject
*)obj
);
1704 PyErr_SetString(PyExc_TypeError
,
1705 "excepted ctypes instance");
1708 if (size
< dict
->size
) {
1709 PyErr_Format(PyExc_ValueError
,
1710 #if PY_VERSION_HEX < 0x02050000
1711 "minimum size is %d",
1713 "minimum size is %zd",
1718 if (obj
->b_needsfree
== 0) {
1719 PyErr_Format(PyExc_ValueError
,
1720 "Memory cannot be resized because this object doesn't own it");
1723 if (size
<= sizeof(obj
->b_value
)) {
1724 /* internal default buffer is large enough */
1728 if (obj
->b_size
<= sizeof(obj
->b_value
)) {
1729 /* We are currently using the objects default buffer, but it
1730 isn't large enough any more. */
1731 void *ptr
= PyMem_Malloc(size
);
1733 return PyErr_NoMemory();
1734 memset(ptr
, 0, size
);
1735 memmove(ptr
, obj
->b_ptr
, obj
->b_size
);
1739 void * ptr
= PyMem_Realloc(obj
->b_ptr
, size
);
1741 return PyErr_NoMemory();
1751 unpickle(PyObject
*self
, PyObject
*args
)
1758 if (!PyArg_ParseTuple(args
, "OO", &typ
, &state
))
1760 result
= PyObject_CallMethod(typ
, "__new__", "O", typ
);
1763 tmp
= PyObject_CallMethod(result
, "__setstate__", "O", state
);
1773 POINTER(PyObject
*self
, PyObject
*cls
)
1780 result
= PyDict_GetItem(_ctypes_ptrtype_cache
, cls
);
1785 if (PyString_CheckExact(cls
)) {
1786 buf
= alloca(strlen(PyString_AS_STRING(cls
)) + 3 + 1);
1787 sprintf(buf
, "LP_%s", PyString_AS_STRING(cls
));
1788 result
= PyObject_CallFunction((PyObject
*)Py_TYPE(&PyCPointer_Type
),
1794 key
= PyLong_FromVoidPtr(result
);
1795 } else if (PyType_Check(cls
)) {
1796 typ
= (PyTypeObject
*)cls
;
1797 buf
= alloca(strlen(typ
->tp_name
) + 3 + 1);
1798 sprintf(buf
, "LP_%s", typ
->tp_name
);
1799 result
= PyObject_CallFunction((PyObject
*)Py_TYPE(&PyCPointer_Type
),
1809 PyErr_SetString(PyExc_TypeError
, "must be a ctypes type");
1812 if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache
, key
, result
)) {
1822 pointer(PyObject
*self
, PyObject
*arg
)
1827 typ
= PyDict_GetItem(_ctypes_ptrtype_cache
, (PyObject
*)Py_TYPE(arg
));
1829 return PyObject_CallFunctionObjArgs(typ
, arg
, NULL
);
1830 typ
= POINTER(NULL
, (PyObject
*)Py_TYPE(arg
));
1833 result
= PyObject_CallFunctionObjArgs(typ
, arg
, NULL
);
1839 buffer_info(PyObject
*self
, PyObject
*arg
)
1841 StgDictObject
*dict
= PyType_stgdict(arg
);
1846 dict
= PyObject_stgdict(arg
);
1848 PyErr_SetString(PyExc_TypeError
,
1849 "not a ctypes type or object");
1852 shape
= PyTuple_New(dict
->ndim
);
1855 for (i
= 0; i
< (int)dict
->ndim
; ++i
)
1856 PyTuple_SET_ITEM(shape
, i
, PyLong_FromSsize_t(dict
->shape
[i
]));
1858 if (PyErr_Occurred()) {
1862 return Py_BuildValue("siN", dict
->format
, dict
->ndim
, shape
);
1865 PyMethodDef _ctypes_module_methods
[] = {
1866 {"get_errno", get_errno
, METH_NOARGS
},
1867 {"set_errno", set_errno
, METH_VARARGS
},
1868 {"POINTER", POINTER
, METH_O
},
1869 {"pointer", pointer
, METH_O
},
1870 {"_unpickle", unpickle
, METH_VARARGS
},
1871 {"_buffer_info", buffer_info
, METH_O
,
1872 "Return buffer interface information (for testing only)"},
1873 {"resize", resize
, METH_VARARGS
, "Resize the memory buffer of a ctypes instance"},
1874 #ifdef CTYPES_UNICODE
1875 {"set_conversion_mode", set_conversion_mode
, METH_VARARGS
, set_conversion_mode_doc
},
1878 {"get_last_error", get_last_error
, METH_NOARGS
},
1879 {"set_last_error", set_last_error
, METH_VARARGS
},
1880 {"CopyComPointer", copy_com_pointer
, METH_VARARGS
, copy_com_pointer_doc
},
1881 {"FormatError", format_error
, METH_VARARGS
, format_error_doc
},
1882 {"LoadLibrary", load_library
, METH_VARARGS
, load_library_doc
},
1883 {"FreeLibrary", free_library
, METH_VARARGS
, free_library_doc
},
1884 {"call_commethod", call_commethod
, METH_VARARGS
},
1885 {"_check_HRESULT", check_hresult
, METH_VARARGS
},
1887 {"dlopen", py_dl_open
, METH_VARARGS
,
1888 "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
1889 {"dlclose", py_dl_close
, METH_VARARGS
, "dlclose a library"},
1890 {"dlsym", py_dl_sym
, METH_VARARGS
, "find symbol in shared library"},
1892 {"alignment", align_func
, METH_O
, alignment_doc
},
1893 {"sizeof", sizeof_func
, METH_O
, sizeof_doc
},
1894 {"byref", byref
, METH_VARARGS
, byref_doc
},
1895 {"addressof", addressof
, METH_O
, addressof_doc
},
1896 {"call_function", call_function
, METH_VARARGS
},
1897 {"call_cdeclfunction", call_cdeclfunction
, METH_VARARGS
},
1898 {"PyObj_FromPtr", My_PyObj_FromPtr
, METH_VARARGS
},
1899 {"Py_INCREF", My_Py_INCREF
, METH_O
},
1900 {"Py_DECREF", My_Py_DECREF
, METH_O
},
1901 {NULL
, NULL
} /* Sentinel */
1906 compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~"