[ctypes] convert pointer to string?

Thomas Heller theller at python.net
Wed May 21 12:33:35 EDT 2008


Neal Becker schrieb:
> In an earlier post, I was interested in passing a pointer to a structure to
> fcntl.ioctl.
> 
> This works:
> 
> c = create_string_buffer (...)
> args = struct.pack("iP", len(c), cast (pointer (c), c_void_p).value)
> err = fcntl.ioctl(eos_fd, request, args)
> 
> Now to do the same with ctypes, I have one problem.
> 
> class eos_dl_args_t (Structure):
>     _fields_ = [("length", c_ulong),
>                 ("data", c_void_p)]
> ...
> args = eos_dl_args_t()
> args_p = cast(pointer(args), c_void_ptr).value
> fcntl.ioctl(fd, request, args_p)  <<< May fail here
> 
> That last may fail, because .value creates a long int, and ioctl needs a
> string.
> 
> How can I convert my ctypes structure to a string?  It _cannot_ be a c-style
> 0-terminate string, because the structure may contain '0' values.
> 
ctypes instances support the buffer interface, and you can convert the buffer
contents into a string:

>>> from ctypes import *
>>> c_int(42)
c_long(42)
>>> buffer(c_int(42))
<read-only buffer for 0x00AE7260, size -1, offset 0 at 0x00B06040>
>>> buffer(c_int(42))[:]
'*\x00\x00\x00'
>>>

Thomas



More information about the Python-list mailing list