Skip to content

[BUG]: Relinquished instance exception for still alive object #879

@WillFroom

Description

@WillFroom

Problem description

I am hitting an issue where nanobind is raising an exception when I am trying to use a C++ object that has already been on a round-trip to python and back but is now wrapped by a outer class.

I have attached a MRE, I get the following error on the use_inner_class line: RuntimeWarning: nanobind: attempted to access a relinquished instance of type ....

I believe what I am doing is valid, but if there is a way around this please let me know.

I haven't tried reverting it but I think that this change: #591 may be being to strict?

Reproducible example code

Extension:

struct InnerClass {};

struct OuterClass {
  std::unique_ptr<InnerClass> inner_class;
};

NB_MODULE(_extension, module_) {
  namespace nb = nanobind;

  nb::class_<InnerClass>(module_, "InnerClass");

  nb::class_<OuterClass>(module_, "OuterClass")
      .def("__init__",
           [](OuterClass* self, std::unique_ptr<InnerClass> inner_class) {
             new (self) OuterClass();
             self->inner_class = std::move(inner_class);
           })
      .def(
          "get_inner_class",
          [](OuterClass* self) { return self->inner_class.get(); },
          nb::rv_policy::reference_internal);

  module_.def("make_inner_class",
              []() { return std::make_unique<InnerClass>(); });

  module_.def("use_inner_class", [](const InnerClass* inner_class) {});
}

Failing test:

  import _extension

  inner_class = _extension.make_inner_class()
  outer_class = _extension.OuterClass(inner_class)
  _extension.use_inner_class(outer_class.get_inner_class()) // RuntimeWarning: nanobind: attempted to access a relinquished instance of type InnerClass

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions