C extension/char array question

Martin von Loewis loewis at informatik.hu-berlin.de
Thu Dec 6 05:54:59 EST 2001


"Bob Greschke" <bob at passcal.nmt.edu> writes:

> What I want to do (today...I think) is create the equivalent of a C
> array of strings like
> 
>    char *Array[] = {"THIS", "THAT"};
> 
> BUT do it in Python such that it can then be passed to an extension
> wrapper function, such that it can then be passed on to a C function
> so that the called function can do something like

Python has no builtin data type that uses an array of char*
internally. It cannot, since the memory management would not be clear.

So you have two options:
1. Implement your own data type. Internally, it would use a char**.
   Externally, you would provide a sequence interface for your type,
   creating string objects on read access.

2. Use a Python list. In Python, you create it with ["THIS","THAT"]
   In C, you need to copy this list into a char*[], element for element.
   You don't do that with PyArg_ParseTuple, but with list accessor methods:

   char **result = malloc(PyList_Length(list)*sizeof(char*));
   for(int i=0;i<PyList_Length(list);i++)
     result[i] = strdup(PyString_AsString(PyList_GetItem(i)));
   
   You can avoid the strdup operations if you can guarantee that the
   Python strings live as long as the char*[] is needed.

HTH,
Martin




More information about the Python-list mailing list