[capi-sig] Beginner Question PyObject* to int
Guilherme Polo
ggpolo at gmail.com
Wed Nov 12 13:06:27 CET 2008
On Tue, Nov 11, 2008 at 12:55 PM, Philipp Heuser <philipp at achtziger.de> wrote:
> Hi all,
>
> I am just starting to use the C API for Python. What I want to do is to use
> an external funtion availabele in C and therfore I want to 'convert' a list
> of floats from Python to an array of floats in C which I can forward to the
> external function. So first step is tp parse a list to C and let the C code
> print the variables! The obviously too simplistic approach is below... When
> I call this function from python, e.g. cpp([1,2,3]) the output is:
> 25180552
> 25180540
> 25180528
>
> Could you be so kind to help me here to get started with using C-functions
> from Python? Where is the error?
>
> Thank you very much and kind regards,
>
> Philipp
>
>
>
> static PyObject *
> cpp_foo(PyObject *self, PyObject* args)
> {
> PyObject* obj;
> PyObject* seq;
> int i, len;
> if(!PyArg_ParseTuple(args, "O", &obj))
> return NULL;
> seq = PySequence_Fast(obj, "expected a sequence");
> len = PySequence_Size(obj);
> PyObject* item;
> int a;
>
> for (i=0; i<len; i++)
> {
> item=PySequence_Fast_GET_ITEM(seq, i);
> a=item; // ?????????????????????????????????????????
Add more '?'s here.
PySequence_FAST_GET_ITEM returns a PyObject, you can't just go and
give it to 'a' to turn it into an integer. Also, this variable 'i'
better be of type Py_ssize_t instead of int.
So, to get your value as a long, first check item is indeed a long
using PyLong_Check(item) and then convert it to a long with
PyLong_AsLong(item):
> printf("%i\n", a);
> }
> Py_DECREF(seq); return None;
> }
>
> _______________________________________________
> capi-sig mailing list
> capi-sig at python.org
> http://mail.python.org/mailman/listinfo/capi-sig
>
--
-- Guilherme H. Polo Goncalves
More information about the capi-sig
mailing list