Skip to content

Commit

Permalink
Create a "holder" object to fix stale reference to array
Browse files Browse the repository at this point in the history
we were creating a reference to an int array, but then that object no
longer was existing, so was being deleted, but we are still trying to
use it. This uses the python capsule mechanism to stash off the array
and then clean it up

Signed-off-by: Kimball Thurston <kdt3rd@gmail.com>
  • Loading branch information
kdt3rd committed Aug 27, 2019
1 parent 311ebb0 commit d2a9dec
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion PyIlmBase/PyImathNumpy/imathnumpymodule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,30 @@
using namespace boost::python;
using namespace PyImath;

template <typename T>
struct Holder
{
Holder( T &a ) : m_val( a ) {}
static void Cleanup (PyObject *capsule)
{
Holder* h = static_cast<Holder*> (PyCapsule_GetPointer (capsule, NULL));
delete h;
}
T m_val;
};

template <typename T>
static void
setBaseObject (PyObject* nparr, T& arr)
{
using converter_type = typename reference_existing_object::apply<T*>::type;
using holder = Holder<T>;

holder* ph = new holder (arr);
PyObject* capsule = PyCapsule_New (ph, NULL, holder::Cleanup);
PyArray_SetBaseObject ((PyArrayObject*) nparr, capsule);
}

static
object
arrayToNumpy_float(FloatArray &fa)
Expand All @@ -59,8 +83,9 @@ arrayToNumpy_float(FloatArray &fa)
if (!a) {
throw_error_already_set();
}
setBaseObject (a, fa);

object retval = object(handle<>(a));
object retval = object (handle<> (a));
return retval;
}

Expand All @@ -81,6 +106,7 @@ arrayToNumpy_V3f(V3fArray &va)
if (!a) {
throw_error_already_set();
}
setBaseObject (a, va);

object retval = object(handle<>(a));
return retval;
Expand All @@ -101,6 +127,7 @@ arrayToNumpy_int(IntArray &va)
if (!a) {
throw_error_already_set();
}
setBaseObject (a, va);

object retval = object(handle<>(a));
return retval;
Expand Down

0 comments on commit d2a9dec

Please sign in to comment.