Hi, > Hi, > > currently I have a problem understanding Py_BuildValue. I have this code: > > static PyObject *function(PyObject *self, PyObject *args) { > PyObject * python_return_value = NULL; > PyObject * dummy = NULL; > double * internal_list; > <snip and forget the rest> > > /* converting to python representation */ > for (i=0; i < limit; i++) { > dummy = Py_BuildValue("d", internal_list[i]); > if (!dummy) return NULL; > PyList_Append(python_return_value, dummy); > Py_DECREF(dummy); dummy = NULL; > } > return python_return_value > } > > This doesn't work. What I see, when invoking the function "function()" in > Python is a list of refcounts, like: [<refcnt 0 at 0x94a29d4>, <refcnt 0 at > 0x94a29e4>, ...]. However, if I change the Py_BuildValue-line to be > dummy = Py_BuildValue("i", (int)internal_list[i]); > I do get the 'right' integer return values. Point is that I really would > like to work with Python-floats afterwards. > > Any idea where a pitfall might be here? >
I see nothing wrong with your code so I'd say it is somewhere else (did you snip any code between the end of the loop and the return?). I've never seen those 'refcnt' objects but a refcount of 0 sounds like you unrefed your objects one extra time by mistake. This would produce a segfault on unix, but maybe not on all platforms ? You should check the return value of PyList_Append() and if it doesn't help trace the content of your list after each iteration to see when the bad things happen (you can check the reference count of an object with obj->ob_refcnt). Finally note that in your case it would be much simpler and more efficient to use the float constructor directly: dummy = PyFloat_FromDouble(internal_list([i])) PS: always use Py_CLEAR(dummy) instead of Py_DECREF(dummy); dummy=NULL; (though it doesn't really matter in this simple case - see http://docs.python.org/api/countingRefs.html) -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list