this is my first post :). I could convert a python extended object into a C++ pointer, but I have a problem. First I will show you my code and then I will explain the problem.
This is my class:
#include <boost/python.hpp>
using namespace boost::python;
class Base
{
public:
virtual const char* HelloWorld() = 0;
};
class BaseWrapper : public Base, public wrapper<BaseWrapper>
{
public:
virtual const char* HelloWorld()
{
if (override f = this->get_override("HelloWorld"))
return call<const char*>(f.ptr());
return "FAILED TO CALL";
}
};
Boost wrapping:
BOOST_PYTHON_MODULE(hello_ext)
{
class_<Base, boost::noncopyable>("Base", no_init);
class_<BaseWrapper, bases<Base> >("BaseWrapper")
.def("HelloWorld", &BaseWrapper::HelloWorld);
}
The Python code (hello.py):
def NewDerived():
import hello_ext
class Derived(hello_ext.BaseWrapper):
def __init__(self):
super(Derived, self).__init__()
def HelloWorld(self):
return "This is a Hello World!!!"
return Derived()
and the main file:
int main()
{
// Start the interpreter.
Py_Initialize();
// Import the module that we need (hello.py)
object module = import("hello");
// Get a C++ pointer of the derived python class.
Base* base = extract< Base* >( module.attr("NewDerived")() );
// Call the HelloWorld function
std::cout << base->HelloWorld() << std::endl;
}
When I run my application I can see at the screen "This is a Hello World!!!" as I expected. So, what is the problem??? Suppose I change the python code to:
def NewDerived():
import hello_ext
class Derived(hello_ext.BaseWrapper):
def __init__(self):
super(Derived, self).__init__()
def HelloWorld(self):
return "This is a Hello" # I CHANGED THIS LINE!!!!
return Derived()
Then, when I run my application again, it crashes, because I got an error in the line:
std::cout << base->HelloWorld() << std::endl;
because base is NULL.
More precisely, the error is "Access violation reading location 0xblablabla". When I debug, the debugguer stops at the function (Boost or Python code, I think)
inline api::object_base::~object_base()
{
Py_DECREF(m_ptr);
}
What do you think???