A weak_ptr safe type_cast. #598
Replies: 2 comments
-
So, if I add a |
Beta Was this translation helpful? Give feedback.
-
I'm not sure if this answers your question, but one thing you can do is simply not to use the STL type casters at all. Instead, you can create bindings for |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I make an extensive use of
std::weak_ptr
. Thanks to nanobind's excellent documentation, I could soon figure out why myweak_ptr
s where becoming invalid prematurely.It turns out that when nanobind creates a
std::shared_ptr
for some object it owns, it creates a brand new control block. This makes theweak_ptr
a virtually useless thing. There are lots of information on problems withenable_shared_from_this
, but of course, the problem does not reside inenable_shared_from_this
. The problem is theweak_ptr
.I do understand very well the design decision behind
std::shared_ptr
'stype_cast
. This post is a mixture of a "feature request" and a request for advice. As a side effect, I suppose the feature would make all the unsolved problems withenable_shared_from_this
, vanish.As far as I understood, in order to have a single control block, as expected by
weak_ptr
, I would have to:Provide a custom
__new__
to always allocate the objects usingshared_ptr
, as described here:https://nanobind.readthedocs.io/en/latest/classes.html#custom-new
This custom
__new__
would have to save a copy of theshared_ptr
, probably using somekeep_alive
trick, just like the currentshared_ptr
type caster does in itsfrom_cpp
.Provide a
shared_ptr
type caster that would return a copy of thisshared_ptr
in itsfrom_python
, pretty much as the current type caster does when the class derives fromenable_shared_from_this
.So, as a feature request, I would love to have all this automatically provided by nanobind through some special
rv_policy::shared_ptr
. I do understand if this is denied, though, because I remember reading something about this sort of things being the driving motive for nanobind's existence, in the first place.As a request for advice, I would love to hear from any interested party, what is your advice for someone in my situation.
Beta Was this translation helpful? Give feedback.
All reactions