On Tue, Aug 09, 2005 at 09:15:17PM -0400, Jeremy Moles wrote: > When using the C API and writing extension modules, how do you normally > pass a structure up into the python module? For instance, if I have a > structure: > > typedef struct Foo { > int x; > int y; > int z; > char xyz[100]; > } Foo; > > Is there an "accepted" way of propagating this upstream? I was thinking > one of these two: > > 1. Returning a enormous tuple of the struct's members using > Py_BuildValue("(iiis)", f.x, f.y, f.z, f.xyz) which would later be > converted to a similar object in Python for clients of my module to use. > > 2. Creating a PyObject and calling PyObject_SetAttrString(O, "x", > Py_BuildValue("i", f.x)) for each member, finally returning a generic > PyObject using the "O" flag in BuildValue. >
The easiest thing to do is to return a dictionary myd = PyDict_New(); assert(myd != NULL); PyDict_SetItemString(myd, "x", PyInt_FromLong((long)mystruct->x)); PyDict_SetItemString(myd, "y", PyInt_FromLong((long)mystruct->y)); PyDict_SetItemString(myd, "z", PyInt_FromLong((long)mystruct->z)); return myd Creating a full fledged object by hand isn't hard and if you are accessing a lot of these it is worth it (instead of creating new dictionaries all the time). But try this first as a quick and dirty, upgrade to a full object if it is still too slow. To see examples of C objects check the python source under Objects/ http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Objects/ (warning, SourceForge CVS is currently being upgraded and is flaky) HTH, -jackdied -- http://mail.python.org/mailman/listinfo/python-list