take this code
#include<boost/python>
namespace bp = boost::python;
bp::list py_points; //initial list
other_class* C; // this class have a bp::list attribute called py_list
// ... some code ....
// in this part C.py_list.ptr() is 0x0
other_class->py_list = py_list; // problem here!!
the problem is with the operator "="
in the debugger in the object_core.hpp file, this is a boost python core file
inline api::object_base& api::object_base::operator=(api::object_base const& rhs)
{
Py_INCREF(rhs.m_ptr);
Py_DECREF(this->m_ptr); // in this line the program fail
this->m_ptr = rhs.m_ptr;
return *this;
}
what is the proper way to use the operator "="
edited
the problem is the stack, if the pointer other_class->py_list is null (or None because the class constructor is not called) the program can´t call the función Py_DECREF (Don't exist references before of the NULL pointer)
the problem is fix calling the constructor
other_class* C = new othe_class(); // fixed!!
The problem is not the assignment operator, the problem is that
py_list
's internalPyObject
pointer is anullptr
. In the majority of cases, the pointer should not be null. From a Python point of view, it should at least manage a reference to the PythonNone
object, as it done by a default constructedboost::python::object
. The default constructor forboost::python::list
creates a new empty list. Hence, the source of the problem likely resides within eitherother_class
's constructor or the "some code" block.To elaborate on the question posed within the title, creating a reference or copying list in Boost.Python is the same as in Python:
The assignment operator will create a reference to a list.
One can slice a list to create a shallow copy.
Here is a complete example with the Python equivalent code annotated in the comments.
Output:
A few points to note in the output:
boost::python::list
objects manage a reference to an empty list.0x804e1ac
isNone
, and none of the list object's internalPyObject
pointer manage a reference to it.list1 = py_list
assignment causeslist1
to manage a reference to the same list managed bypy_list
. This is exhibited in the output bylist1
initially managing a reference to0xb70da98c
, but post-assignment, it manages a reference to0xb707024c
. Withlist1
andpy_list
managing the same list, a change to the list through one handle can be observed in the other handle.PyObject
internal point forlist2
manages a different reference (0xb707cb0c
) thanlist1
's pointer (0xb707024c
).