[PyQt] sip: how to make a python instance owned by C++ without using a parent

Phil Thompson phil at riverbankcomputing.com
Tue Aug 14 09:22:26 BST 2012


On Mon, 13 Aug 2012 23:07:07 +0200, Mathias.Born at gmx.de wrote:
> Hi,
> 
> I have a C++ class "Project", which I expose to Python
> via sip.
> In Python, I sub-class:
> 
> class Derived(Project):
>       ...
> 
> In addition, there is a Python factory function which creates an
> instance of "Derived" and returns it:
> 
> def f():
>     return Derived(...)
> 
> I call this function from withing C++, and feed the return
> value into "sipConvertToType", in order to create a wrapper
> of type "Project", so I can call methods of the returned
> "Derived" instance from within C++, using the wrapper.
> 
> Since the "Derived" instance is created by Python, it is
> owned by Python.
> Is there a way to transfer ownership to C++ without using any
> additional objects? I want the Python part to stick to the
> C++ wrapper until the latter is destroyed, at which point
> the Python part should also be automatically disposed, without
> any need to micro-manage the Python part myself.

That will happen automatically anyway so long as Derived has a virtual
dtor. The Python object will only ever be destroyed when its reference
count reaches 0, irrespective of the state of the C++ instance.

> In the sip sources, I can see a flag "SIP_CPP_HAS_REF" that
> might just achieve that, but there appears to be no official
> way to use it.

To transfer ownership of a Python object to C++ (ie. to control whether
the Python dealloc code calls the C++ dtor) use...

http://www.riverbankcomputing.com/static/Docs/sip4/c_api.html#sipTransferTo

Phil


More information about the PyQt mailing list