14.14.1.7 Specifying the required argument types (function prototypes)
From Python 2.5
14.14.1.7 Specifying the required argument types (function prototypes)
It is possible to specify the required argument types of functions exported from DLLs by setting the argtypes attribute.
argtypes must be a sequence of C data types (the printf
function is probably not a good example here, because it takes a
variable number and different types of parameters depending on the
format string, on the other hand this is quite handy to experiment
with this feature):
>>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
>>> printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2)
String 'Hi', Int 10, Double 2.200000
37
>>>
Specifying a format protects against incompatible argument types (just as a prototype for a C function), and tries to convert the arguments to valid types:
>>> printf("%d %d %d", 1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ArgumentError: argument 2: exceptions.TypeError: wrong type
>>> printf("%s %d %f", "X", 2, 3)
X 2 3.00000012
12
>>>
If you have defined your own classes which you pass to function calls,
you have to implement a from_param class method for them to be
able to use them in the argtypes sequence. The from_param
class method receives the Python object passed to the function call,
it should do a typecheck or whatever is needed to make sure this
object is acceptable, and then return the object itself, it's
_as_parameter_ attribute, or whatever you want to pass as the C
function argument in this case. Again, the result should be an
integer, string, unicode, a ctypes instance, or something having
the _as_parameter_ attribute.
See About this document... for information on suggesting changes.