[C++-sig] Problem with extracting a C++ object from python
Matt
mjkeyes at sbcglobal.net
Fri Oct 28 23:50:38 CEST 2005
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