I need to create a new list via the python C API containing new copies of objects of a Quaternion
class I've written (in C++). [Actually, I'd really like a numpy array, but any sort of sequence would do.] But I'm getting seg faults with everything I've tried. I'm terrible with pointers, so that's not a big surprise. I'm thinking maybe I need to give python ownership of the objects I create with new
.
The best I've gotten so far appears below. Am I not supposed to copy-construct the Quaternion while new
ing it? Am I doing something else stupid? Do I need to tell python it owns the reference now? Should the returned list exist and live a happy life, as I expected?
PyObject* Objectify(std::vector<Quaternion>& v) {
Py_ssize_t size = v.size();
PyArrayObject* list = (PyArrayObject*) PyList_New(size);
for(Py_ssize_t i=0; i<size; ++i) {
PyObject* o = (PyObject*) new Quaternion(v[i]);
PyList_SET_ITEM((PyObject*)list, i, o);
}
return PyArray_Return(list);
}
I can verify that the list still has the correct elements just before the return. That is, after the loop above, I make a new loop and print out the original values next to the list values, and they match. The function will return, and I can keep using python. But once the list is used outside the loop, the segfaults happen.
[Actually, this is all being done in SWIG, and this code is found in a typemap with slightly different variable names, but I can look in the _wrap.cxx
file, and see that it's just how I would have written it.]