passing a tuple of floats to C++

Alex Martelli aleax at aleax.it
Wed Jul 24 04:12:10 EDT 2002


Joe Connellan wrote:

> How would I go about passing a tuple of floats of an arbitrary (but
> large) size to C++ - would I use PyArg_ParseTuple()?

Fastest and most general is to start with:

        PyObject* seq = PySequence_Fast(thetuple, "ain't a sequence!")

which gives you the same object as thetuple when thetuple is indeed
a tuple, or list, but also lets you pass other sequences and then
converts them to lists internally.  After this, seq will be NULL if
thetuple was not a sequence, so the next statement should be:

        if(!seq)
            return 0;

to propagate the exception.  Once you do have seq, use the macros
PySequence_Fast_GET_SIZE to get its length (so you know how large
a C++ std::vector to make -- not crucial, but .reserve()ing the right
size DOES make things much faster!) and loop using another macro,
PySequence_Fast_GET_ITEM, to access the items and put them into
the std::vector.

Remember to decref seq when done!


Not sure if this is documented in the Python docs -- it IS well
documented in Include/abstract.h in the source distribution (not
a few things regarding the C API's are only documented in the
sources -- not sure if this is one of them -- anyway, you DO
want to skim the Python sources for instruction and examples if
you're at all serious about interfacing Python with C & the like).


Alex




More information about the Python-list mailing list