C API: array of floats/ints from python to C and back

Ivan Illarionov ivan.illarionov at gmail.com
Sat Dec 27 23:47:26 EST 2008


On Dec 28, 12:45 am, "Daniel Fetchinson" <fetchin... at googlemail.com>
wrote:
> I'm trying to write an extension module in C which contains a single
> function with the following prototype:
>
> void func( int N, int * arg1, int * arg2, int * ret );
>
> Here arg1 and arg2 are length N arrays, and the function computes ret
> which is also an N length array. From python I'd like to call this
> function as
>
> ret = func( [ 1, 2, 3 ], [ 2, 3, 4] )
>
> I've read through the docs athttp://docs.python.org/extending/extending.htmland alsohttp://docs.python.org/c-api/arg.htmlfrom which I learned how to pass
> a fixed number of basic datatypes (int, float, string) from python to
> C and back. What I don't know is how to pass an array back and forth.
>
> As far as I can see PyArg_ParseTuple is the function I should use for
> converting the python arguments to C but the format string passed to
> PyArg_ParseTuple can only be one of the basic data types ("s", "i",
> etc) or a generic python object ("O").
>
> Does this mean that I can only pass the arrays from python to C as
> generic python objects and in a later operation I need to get the
> elements from this generic python object, construct a C array and pass
> that to the C function? Since I assume this is a frequent operation
> I'd think there are some shortcuts, aren't there? Or what's the
> simplest way of doing this?
>
> Cheers,
> Daniel
>
> --
> Psss, psss, put it down! -http://www.cafepress.com/putitdown

Hi Daniel,

Consider using this:
http://docs.python.org/c-api/objbuffer.html

This *IS* a shortcut, real shortcut.



More information about the Python-list mailing list