C extension question

Matimus mccredie at gmail.com
Thu Nov 1 13:50:04 EDT 2007


On Nov 1, 7:07 am, chris.ceno... at gmail.com wrote:
> I am currently trying to port some Python and Python C extension code
> to C#, and am having trouble understanding what is happening in a
> piece of the code.
>
> The pertinent pieces of code are below, and my question follows the
> snippets:
>
> in foo.py:
>   (mgrid,xgrid,ygrid,zgrid,ngrids) = IP.CreateGridCell()
>
> in IP.c:
>   static PyObject *PyCreateGridCell()
>   {
>     GRIDCELL *grid = alloc(...);
>     for(i=0; i<length; i++)
>     {
>       grid[cnt] = .... //etc fill in grid array
>       cnt++;
>     }
>
>     PyObject *GRIDRET = PyCObject_FromVoidPtr((void *)grid,NULL);
>     return Py_BuildValue("Oi",GRIDRET,cnt-1);
>
>   typedef struct {
>     XYZ p[8];
>     double val[8];
>   } GRIDCELL;
>
>   typedef struct {
>     double x,y,z;
>   } XYZ;
>
> So my question is (and I hope it's not too silly a question), what is
> happening to the grid array pointer in the C code that it maps to
> multiple variables (which all are arrays) on the python side.  Is the
> grid variable being assigned to mgrid, xgrid, ygrid and zgrid whole,
> or is it being split somehow (and if so, how)?  Thanks for the help.

PyCreateGridCell uses [1]Py_BuildValue to generate a tuple containing
a Object (its not really clear to me exactly what this object is) and
an integer. From the looks of it I would say that PyCreateGridCell
does not return something that can be unpacked into 5 things like the
python code suggests. Hoever, there is no guarantee that
PyCreateGridCell is the function that gets called by Python when
IP.CreateGridCell is called. You have to look at the method table to
see what it maps to. I would read the introduction [2] at least to the
Extending and Embedding documentation.

Why do you need to do this anyway. If you _need_ to use .NET you could
save time by using IronPython instead of rewriting the whole thing in
C#.

[1] http://docs.python.org/api/arg-parsing.html#l2h-216
[2] http://docs.python.org/ext/intro.html

Matt




More information about the Python-list mailing list