Cpoying a PyList to a C string array

Klaas mike.klaas at gmail.com
Tue Dec 19 13:58:36 EST 2006


Sheldon wrote:
> The code below is a rookie attempt to copy a python list of strings to
> a string array in C. It works to some extent but results in memory
> problems when trying to free the C string array. Does anyone know how
> to do this properly?

You have numerous problems in this code.  The most important problem is
that you are referring to global variables which appear to be c structs
but you don't provide the definition (e.g., "work").  However, I can
guess some of the issues:

>   for (i = 0; i < work.sumscenes; i++) {
>     msgop = PyList_GetItem(work.msgobj, i);
>     work.msg_scenes[i] = PyString_AsString(msgop);
>     ppsop = PyList_GetItem(work.ppsobj, i);
>     work.pps_scenes[i] = PyString_AsString(ppsop);
>   }

PyString_AsString returns a pointer to the internal buffer of the
python string.  If you want to be able to free() it (or indeed have it
exist for beyond the lifetime of the associated python string), you
need to malloc() memory and strcpy() the data.  If the strings contain
binary data, you should be using PyString_AsStringAndSize.  see
http://docs.python.org/api/stringObjects.html.

I notice that you are doing no error checking or ref counting, but my
(inexperienced python c programming) opinion is that it should work
(neither api could potentially call python code, so I don't think
threading is an issue).

>   for (i = 0; i < NumberOfTiles; i++) {
>     tileop  = PyList_GetItem(work.tileobj, i);
>     work.tiles[i] = PyString_AsString(tileop);
>     sceneop = PyList_GetItem(work.nscenesobj, i);
>     work.nscenes[i] = PyInt_AsLong(sceneop);
>   }
>   return 1;

Similarly.

-Mike




More information about the Python-list mailing list