The create_string_buffer()
The create_string_buffer()
is still available as an alias), as well as the c_string() function from earlier ctypes
releases. To create a mutable memory block containing unicode characters of the C
type wchar_t use the create_unicode_buffer() function.
Note that printf prints to the real standard output channel, not to sys.stdout, so
these examples will only work at the console prompt, not from within IDLE or
PythonWin:
>>>
Hello, World!
14
Hello, World!
14
42 bottles of beer
19
As has been mentioned before, all Python types except integers, strings, and bytes
objects have to be wrapped in their corresponding ctypes type, so that they can be
converted to the required C data type:
>>>
31
>>>
You can also customize ctypes argument conversion to allow instances of your own
classes be used as function arguments. ctypes looks for an _as_parameter_
attribute and uses this as the function argument. Of course, it must be one of integer,
string, or bytes:
>>>
...
42 bottles of beer
19
>>>
If you don’t want to store the instance’s data in the _as_parameter_ instance
variable, you could define a property which makes the attribute available on
request.
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(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)
37
>>>
>>>
X 2 3.000000
13
>>>
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, its _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, bytes, a ctypes instance, or an object
with an _as_parameter_ attribute.
Return types
By default functions are assumed to return the C int type. Other return types can be
specified by setting the restype attribute of the function object.
Here is a more advanced example, it uses the strchr function, which expects a
string pointer and a char, and returns a pointer to a string: