Returns a list of new user class objects in the python C API

I need to create a new list via the python API containing new copies of the class objects Quaternionthat I wrote (in C ++). [Actually, I really need a numpy array , but any sequence will do.] But I get seg errors with everything I tried. I'm terrible with pointers, so this is not a big surprise. I think maybe I need to grant python rights to the objects that I create with new.

The best I've received so far is shown below. I do not have to copy-build Quaternion, but newhim? Am I doing something else stupid? Should I tell python that it owns the link 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 items immediately before returning. That is, after the loop above, I create a new loop and print the original values ​​next to the list values, and they match. The function will return, and I can continue to use python. But as soon as the list is used outside the loop, segfaults occur.

[In fact, all this is done in SWIG, and this code is in a sample map with slightly different variable names, but I can look in the file _wrap.cxxand see how exactly I would write it.]

+1
1

, , . PyObject; python. , , PyArrayObject , , dastrobu .

, SWIG, Quaternion - PyObject ( - , SWIG). , , , ( numpy, ):

npy_intp size = 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((new Quaternions::Quaternion(v[i])),
                                      SWIGTYPE_p_Quaternions__Quaternion, SWIG_POINTER_OWN);
  if(!qobj) {SWIG_fail;}
  data[i] = qobj;
  Py_INCREF(qobj);
}

, PyArray_SET_ITEM , segfaults, . , NPY_OBJECT...

, , - .

+1

All Articles