Help with C API

Nick Jacobson nicksjacobson at yahoo.com
Sat May 1 06:08:07 EDT 2004


vincent wehren <vincent at visualtrans.de> wrote in message news:<c6vfmv$grq$1 at news1.tilbu1.nb.home.nl>...
> Nick Jacobson wrote:
> ...
> > I'd like to do the reverse: take an C array (say, with 100 elements)
> > and copy its elements into a Python list.  But I don't know where to
> > start...there's no PySequence_Fast_INSERT or even PySequence_Insert
> > function, for example.  Can I create an empty list in the API or
> > should I just pass one in from Python?
> > 
> > Can someone please help with this?  Thanks in advance!!
> > 
> > --Nick
> 
> http://docs.python.org/api/listObjects.html is probably a good start
> 
> Regards,
> Vincent Wehren


Thank you!

This is what I ended up writing:

static PyObject *ex_arytopylist(PyObject *self, PyObject *args) {
	PyObject *seq = NULL, *fitem = NULL;
	double dbar[] = { 1, 2, 3 };
	int i, seqlen = sizeof(dbar) / sizeof(double);

	seq = PyList_New(0);
	if (!seq) return NULL;

	for (i=0; i < seqlen; i++) {
		fitem = PyFloat_FromDouble(dbar[i]);
		if (!fitem) { Py_DECREF(seq); return NULL; }
		if (PyList_Append(seq, fitem))
                { Py_DECREF(fitem); Py_DECREF(seq); return NULL; }
		Py_DECREF(fitem);
	}
	return Py_BuildValue("O", seq);
}

My only question is, since PyList_New(0) and Py_BuildValue both
increment the ref count of seq, is it garbage collected properly?  Or
perhaps I should just write:

return seq;

Thanks!



More information about the Python-list mailing list