help with c <-> python buffer transfer
John Machin
sjmachin at lexicon.net
Fri Aug 11 23:45:49 EDT 2006
tkirke at gmail.com wrote:
> This is the part I need help with. I've also used PyBuffer_...
> subroutines which gave similar problems. Thanks for all of your other
> comments, but I was hoping someone could just tell me what was wrong
> with the code without having to worry about all of the other things
> that could go wrong.
> For completeness here is the complete c++ module & python output
>
> //=======================================================================
> // Boost Includes
> //==============================================================
> #include <boost/python.hpp>
> #include <boost/cstdint.hpp>
> #include <boost/python/def.hpp>
> #include <boost/python/args.hpp>
> #include <boost/python/overloads.hpp>
>
> // Using
> =======================================================================
> using namespace boost::python;
>
> static PyObject * proc_buf(PyObject *self, PyObject *args) {
> PyObject *resultobj;
> char* output_samples;
> int len;
> if (!PyArg_ParseTuple(args,"s#|l",&output_samples, &len)) {
Sorry, I read that too quyickly. You need THREE receptors, one for "s",
2nd for "#", 3rd for "l".
e.g. something like:
int len;
long third_arg; /* needs initialisation */
if (!PyArg_ParseTuple(args,"s#|l",&output_samples, &len,
&third_arg)) {
> return NULL; /* wrong arguments provided */
> }
> for (int i=0;i<len;i++) output_samples[i] *= 2;
> resultobj = PyString_FromStringAndSize(output_samples, len);
> return resultobj;
> }
> // Module
> ======================================================================
> BOOST_PYTHON_MODULE(spuctest)
> {
> def("pass_buf",&proc_buf);
> }
>
> # python code
> ....
> buffy = mf.read()
> print type(buffy)
> buf = pass_buf(buffy, len(buffy))
> print type(buf)
> #
>
> #python output
> <type 'buffer'>
> <type 'Nonetype'>
I'd guess the return value of None was fortuitous -- when I tried your
code using C, the call to pass_buf just crashed. With the above fix,
the problem goes away:
|>>> import procbuf
|>>> foo = '\x01\x03\xff'
|>>> x = procbuf.passbuf(foo)
|>>> x
'\x02\x06\xfe'
HTH take2 :-)
John
More information about the Python-list
mailing list