help with c <-> python buffer transfer
John Machin
sjmachin at lexicon.net
Fri Aug 11 19:24:49 EDT 2006
tkirke at gmail.com wrote:
> How does one transfer a buffer object from python -> c and back again
> (assuming the data gets modified)?
> I can't seem to get this or anything else to work, but am clueless as
> to what I'm doing wrong
>
>
> using namespace boost::python;
Looks like C++, not C.
>
> static PyObject * proc_buf(PyObject *self, PyObject *args) {
[I'm not familiar with the boost gadget, but ...] Doesn't "static" mean
that this function is *not* externally visible?
> PyObject *resultobj;
> char* output_samples;
> int len;
> if (!PyArg_ParseTuple(args,"s#|l",&output_samples, &len)) {
You have made the length an optional argument, but not initialised the
receiving variable "len". Nothing to do with your current problem, but
highly dangerous.
> return NULL; /* wrong arguments provided */
> }
> for (int i=0;i<len;i++) {
> output_samples[i] *= 2; // for example
> }
This is updating the internal representation of the input in situ. Not
a very good idea at all. Take a copy. Return the updated copy.
> resultobj = PyString_FromStringAndSize(output_samples, len);
> return resultobj;
> }
>
>
> This compiles ok, but when in python I do
>
Put print repr(bufx), type(bufx) here so that we're all clued in on
what you are talking about. You say "transfer a buffer object" but your
C[++] is returning a string object.
> buf = proc_buf( bufx, len(bufx)
You are missing both a module name and a ")" here. It should look
something like:
buf = theextensionmodule.proc_buf( bufx, len(bufx))
Please *always* copy/paste the actual code that you executed.
> len(buf)
>
> I get
> len() of unsized object
Please *always* copy/paste the actual error message & stack trace that
you get.
Try print repr(buf), type(buf) here; it might give you a clue as to
what type of object you have that is unsized. On the surface this is a
mystery, as (based on the info that you have supplied), "buf" should be
a string.
HTH .... alternatively come up a level or three and tell us what your
basic requirement is; maybe it can be solved more easily in Python or
Pyrex.
Cheers,
John
More information about the Python-list
mailing list