<div dir="ltr">So I'm trying to create a boost python module that simply creates and returns a numpy array, <div>but the function crashes (sometimes) and it doesn't ever seem to crash on Python 2.</div><div><br></div><div>Here's the source code I made:</div><div><div><br></div><div>#include <boost/python.hpp></div><div>#include <numpy/ndarrayobject.h></div></div><div><div><br></div><div>using namespace boost::python;</div><div><br></div><div>object create_numpy_array() {</div><div><span class="" style="white-space:pre">        </span>npy_intp dims = 1;</div><div><span class="" style="white-space:pre"> </span>long* data = new long[1];</div><div><span class="" style="white-space:pre">  </span>data[0] = 1;</div><div><span class="" style="white-space:pre">       </span>PyObject* obj = PyArray_SimpleNewFromData(1, &dims, PyArray_LONGLTR, data);</div><div><span class="" style="white-space:pre">    </span>boost::python::handle<> handle(obj);</div><div><span class="" style="white-space:pre"> </span>boost::python::numeric::array arr(handle);</div><div><span class="" style="white-space:pre"> </span>return arr.copy();</div><div>}</div></div><div><br></div><div><div>BOOST_PYTHON_MODULE(create) {</div><div><span class="" style="white-space:pre">     </span>import_array();</div><div><span class="" style="white-space:pre">    </span>numeric::array::set_module_and_type("numpy", "ndarray");</div><div><span class="" style="white-space:pre">       </span>def("numpy_array", &create_numpy_array);</div><div>}</div></div><div><br></div><div><br></div><div>using a simple python script to test:</div><div><br></div><div>import create</div><div>print(create.numpy_array())</div><div><br></div><div><br></div><div>The stack trace indicates that the crash occurs on a boost::python::handle destructor trying to decrease the ref count of a PyObject with a ref count of 0.</div><div><br></div><div>I've tried this on both Windows 7 and Ubuntu 16.04 both 64-bit.</div><div><br></div><div>Thank you.</div></div>