[C++-sig] Problem with extracting a C++ object from python

Matt mjkeyes at sbcglobal.net
Sat Oct 29 06:01:20 CEST 2005


I think I found a workaround.  If I receive the call from the base class 
into a str object and extract a const char * from it, then I get no dangling 
references.  I'm guessing that since this object is never passed to Python 
(I assume) that the dangling pointer comes from that.  Not sure...

"Matt" <mjkeyes at sbcglobal.net> wrote in message 
news:dju6nq$ah8$1 at sea.gmane.org...
> Okay, now I have another question.  Let's consider the same scenario with 
> a slight modification:
>
> class Root
> {
> public:
>    Root() {}
>    virtual ~Root() {}
> }
>
> class Base : public Root, public wrapper<Root>
> {
> public:
>    Base() {}
>    virtual ~Base() {}
>
>    virtual void DoSomethingBase()
>    {
>        try
>        {
>            this->get_override("DoSomething")();
>        }
>        catch(...)
>        {
>            PyErr_Print();
>        }
>    }
>
>    virtual const char * GetNameBase()
>    (
>        std::string sResult;
>        try
>        {
>            const char *szResult = this->get_override("GetName")();
>            sResult = szResult;
>        }
>        catch(...)
>        {
>            PyErr_Print();
>        }
>    }
> };
>
> class Derived : public Base
> {
> public:
>    Derived() {}
>    virtual ~Derived() {}
>
>    virtual void DoSomethingDefault()
>    {
>        const char *sName = GetNameBase();        //<-----Python error pops 
> up here
>        //...do stuff
>    }
>
>    virtual const char * GetNameDefault()    {return m_sName.c_str();}
>
>    std::string m_sName;
> };
>
> BOOST_PYTHON_MODULE(MyModule)
> {
>    class_<Derived, boost::noncopyable>("PyDerived");
>        .def("DoSomething",    &Base::DoSomethingBase, 
> &Derived::DoSomethingDefault)
>        .def("GetName",          &Base::GetNameBase, 
> &Derived::GetNameDefault)
>        ;
> }
>
> In Python:
>>>>import MyModule
>>>>x = PyDerived()
>>>>x.DoSomething()
>
> The result is this:
> "ReferenceError: Attempt to return dangling pointer to object of type: 
> char"
>
> It occurs in PyDerived::DoSomethingDefault when GetNameBase is called 
> (which calls back to PyDerived::GetName).  I'm trying to implement this 
> type of scenario on several objects to make them fully overrideable 
> classes in Python.
>
> Any advice on why this would happen with the c_str in a std::string?  Is 
> there a better way (or a "right" way) to do this type of thing?
>
> Thanks again guys! 






More information about the Cplusplus-sig mailing list