[C++-sig] bp::wrapper class returning reference type

Charles Solar charlessolar at gmail.com
Wed Sep 22 23:29:02 CEST 2010


I have a bp::wrapper wrapping an interface for use in python.  Several
functions return reference types of other objects, for example:

class IFoo
{
    virtual const IBar& getBar() const = 0;
}

I found that to get boost python to handle this scenario correctly and
eliminate any 'returning address of local variable' warnings I had to
trick the result converter like so:

class Foo_wrapper : IFoo, bp::wrapper< IFoo >
{
    Bar _bar;
    const IBar& getBar() const
    {
        _bar = *(IBar*)this->get_override( "getBar" )();
        // return *(IBar*)this->get_override( "getBar" )();   <- works
as well but maybe less safe?
    }
}

I was messing with this problem for the last day and a half and this
finally worked.  From what I understand the method converter is
tricked into returning an IBar* by the cast, then I use the copy
constructor to make a concrete bar locally which is finally returned
as a reference to the calling code.

My first concern is if this is a 'proper' solution for this problem.
I found that by just doing
const IBar& getBar() const
{
    return (IBar&)this->get_override( "getBar" )();
}

I would get crashes because the object returned from get_override
would be destroyed before I can copy it.  IBar is abstract so most
'correct' uses will not work.

If this solution is acceptable my question is how is the result
converter dealing with the IBar* cast.  Is it depending on me to
delete the pointer?  Does this solution cause massive memory leaks?
Or will cleaning up the python object clean up the pointer as well?  I
want to implement a 'proper' solution to minimize future potential
problems.

Thank you


More information about the Cplusplus-sig mailing list