Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create a "holder" object to fix stale reference to array #534

Merged
merged 2 commits into from
Aug 27, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion PyIlmBase/PyImathNumpy/imathnumpymodule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,29 @@
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 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 +82,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 +105,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 +126,7 @@ arrayToNumpy_int(IntArray &va)
if (!a) {
throw_error_already_set();
}
setBaseObject (a, va);

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