Embedding Python in C++ application: Question #1

Russell Turpin russell_turpin at hotmail.com
Mon Dec 3 19:16:05 EST 2001


I'm embedding Python in a commercial C++ application, in order
to provide a scripting capability. 

The application provide some functions that need to be 
surfaced on the scripting side, one of which returns a lot of 
data. On the Python side, this data should be received as an 
array of objects. (The array itself is part of a larger object, 
but that doesn't seem relevant here.)

Thinking about how to do this, the Py_ interface presents
some difficulties, though I hope this is due largely to my
inexperience with it. The first problem is that it seems
designed to convert a known, fixed number of values:

  pResult = Py_BuildValue("[(iid), (iid)]", a[0]->x, a[0]->y, a[0]->z,
                                            a[1]->x, a[1]->y, a[1]->z);

That would be cool if the array always had two elements, 
rather than anywhere from two to a few thousand. Of course, 
I can iterate, but whenever I have frequent iteration over 
lots of things my intuition is to push the iteration as far
down as practical. I would prefer to use a function, Convert(), 
that generates a Python tuple or object from the C++ object of
which a[] is an array, and then pass this to something that 
builds the Python array:

  pResult = Py_BuildArray("O&", Convert(), a, iStart, iStop);

Py_BuildArray doesn't exist to my knowledge. It would apply
Convert() to each instance of a[] from a[iStart] to a[iStop],
creating a Python array of the resulting Python objects.

Is there something like this? Is there a better way of doing
this than just iterating on Py_BuildValue()? Am I missing 
something obvious? 

All help much appreciated!

Russell



More information about the Python-list mailing list