Giving C++ ownership of class object in pybind11 #5470
Unanswered
VaradDerivative
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have an application in which I want to expose a C++ class
MyClass
to python using pybind. Since I want python to be embedded within c++, I use PYBIND11_EMBEDDED_MODULE to expose my c++ class.Now, I want to it to work in such a way that I take an already instantiated instance of
MyClass
, saymyInstance
- and create the python instance from this. To achieve this, I usepy::cast()
Now, the issue that I'm trying to solve is - I want my c++ application to have sole ownership of
myInstance
. I wantmyPyInstance
to have nothing to do with the lifetime ofmyInstance
. And that ifmyInstance
is destructed at some point,myPyInstance
should know about it and handle that case.Is there some kind of weak ref workflow that I can use? pybind natively allows for unique_ptr or shared_ptr workflow, but none of those work for my case.
The custom smart pointer workflow sounds promising, and I pursued a solution where the smart pointer held a holder to
myInstance
. I hoped that.get()
on the smart pointer would be called when the individual methods are called, allowing the smart pointer to check whethermyInstance
is alive or not. But it looks like.get()
is called whencast()
is called and the result is held onto.There is
return_value_policy::reference
but it doesn't handle the case of the object being deleted by the c++ application while still being referenced by python, and this is a crucial case for me.Beta Was this translation helpful? Give feedback.
All reactions