Return List Of New Custom-class Objects In Python C Api
Solution 1:
Now that I see it, it's obvious. I can't just cast an arbitrary type to a PyObject
; it needs to actually have some actual python structure. E.g., I'm thinking a PyArrayObject
can be cast as such, but my random class needs to be wrapped, as dastrobu explained on my other question.
As I mentioned, I'm using SWIG, which already wraps Quaternion
into some kind of PyObject
(though it's given some other name to denote that it's made by SWIG). So, while this doesn't answer my question in general, the following does exactly what I need (including creating numpy arrays, rather than just lists):
npy_intpsize= v.size();
PyArrayObject *npy_arr = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNew(1, &size, NPY_OBJECT));
PyObject** data = static_cast<PyObject**>(PyArray_DATA(npy_arr));
for(npy_intp i=0; i<size; ++i) {
PyObject* qobj = SWIG_NewPointerObj((newQuaternions::Quaternion(v[i])),
SWIGTYPE_p_Quaternions__Quaternion, SWIG_POINTER_OWN);
if(!qobj) {SWIG_fail;}
data[i] = qobj;
Py_INCREF(qobj);
}
I should also point out that I originally tried using PyArray_SET_ITEM
to assign the items of the list in this code, but kept getting segfaults, which is why I use this weird method. I wonder if it has something to do with the offsets of the NPY_OBJECT
...
Anyway, I hope that helps someone else in the future.
Post a Comment for "Return List Of New Custom-class Objects In Python C Api"