Skip to content

Could unchecked views prevent garbage collection of the underlying arrays? #961

Closed
@anntzer

Description

@anntzer

Issue description

Unchecked views appear to not prevent garbage collection of the underlying array (object). Unless I am mistaken, it should be possible for them to incref the underlying object upon construction of the unchecked view and decref it upon destruction, for a minimal cost; I do not see a case where the opposite behavior is desirable.

Reproducible example code

#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>

namespace py = pybind11;

int foo() {
    auto a =
        py::module::import("numpy").attr("zeros")(1)
        .cast<py::array_t<double>>().mutable_unchecked<1>();
    auto b =
        py::module::import("numpy").attr("zeros")(1)
        .cast<py::array_t<double>>().mutable_unchecked<1>();
    a(0) = 1;
    // Rely on the fact that after a and b are (usually) allocated at the same position as the
    // first one has been immediately garbage collected.
    py::print(a(0), b(0));
}

PYBIND11_PLUGIN(python_example) {
    py::module m("python_example");
    m.def("foo", &foo);
    return m.ptr();
}
$ python -c 'from python_example import *; foo()'
1.0 1.0  # Should be 1.0 0.0 if a did not get GC before b gets allocated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions