[Python-Dev] buffer interface for C extensions
Dan Lenski
dlenski at gmail.com
Mon May 19 00:59:05 CEST 2008
Hi all,
I've written a small C extension to submit commands to SCSI devices via
Linux's sg_io driver (for a camera hacking project). The extension is
just a wrapper around a couple ioctl()'s with Pythonic exception handling
thrown in. One of my extension methods is called like this from python:
sg.write(fd, command[, data, timeout)
Both command and data are binary strings. I would like to be able to use
either a regular Python string or an array('B', ...) for these read-only
arguments. So I tried to use the "t#" argument specifier to indicate that
these arguments could be either strings or objects that implement the read-
only buffer interface:
if (!PyArg_ParseTuple(args, "it#|t#i:write", &sg_fd, &cmd,
&cmdLen, &buf, &bufLen, &timeout))
return NULL;
Now, this works fine with strings, but when I call it with an array I get
a TypeError:
TypeError: write() argument 2 must be string or read-only character
buffer, not array.array
So, I then tried changing "t#" to "w#" to indicate that the arguments must
implement the /read-write/ buffer interface. Now the array objects work,
but when I try a string argument, I naturally get this error:
TypeError: Cannot use string as modifiable buffer
So here's what I don't understand. Why doesn't the "t#" argument
specifier support read-write buffers as well as read-only buffers? Aren't
read-write buffers a *superset* of read-only buffers?? Is there something
I'm doing wrong or a quick fix to get this to work appropriately?
Thanks for any help!
Dan
More information about the Python-Dev
mailing list