harold fellermann <harold@imb-jena.de> writes:
hi.
As you might know in the meanwhile, I want to insert references (not instances) of C++ objects into a boost::python::list. I thought that calling
CPPObject cpp_obj; list.insert(0,handle<>(borrowed(cpp_obj)))
would do the thing. According to the documentation I need to inherit from PyObject:
class CPPObject : public PyObject { // [...] };
and as soon as I do this, my code is compiled without error, but failed in the constructor of CPPObject. As stated in the Python/C-API, "you never declare an automatic or static variable of type PyObject, only pointer variables of type PyObject* can be declared." So how can the references be stored?
First, please do what Ralf said and read the fine tutorial front-to-back before proceeding, or trying anything I've said below. You need to get a better sense of how the library works in order to understand any advice we can give here. One way, but not neccessarily a safe one, to get a Python object into your list which wraps a reference to a C++ object, is list.insert(0, boost::ref(cpp_obj)); I say "not neccessarily safe" because there is nothing here to help manage the lifetime of the C++ object properly; if it is destroyed before the last Python reference you could crash the program with Python code. Since you say: "My general ambition is to reimplement some classes originally written in python. So my intention is not to not intrude the underlying C++-classes, but rather to not intrude the overlying python-classes" I would recommend that you manage all your C++ objects with boost::shared_ptr<>. This is probably the most-foolproof way of getting lifetime issues sorted out, since boost::shared_ptr magically takes care of many issues; see http://article.gmane.org/gmane.comp.python.c++/2530/match=shared+ptr -- Dave Abrahams Boost Consulting www.boost-consulting.com