Search code examples
c++boostboost-python

Error with Boost.Python when returning a reference to a custom object


EDIT: I noticed my question was not clear enough; I hadn't specified n0 was an attribute of Edge.

I have two classes Nodes and Edges. Edge is defined (I omitted lots of methods and attributes that are of no interest here):

class Edge()
{
  Node& n0;
public:
  const Node& N0() const;
};

The accessor is coded as follows:

Node const& Edge::N0() const
{
  return n0;
};

where n0 is a private reference to a Node() instance. The problem is that, while trying to expose this function with the following code:

class_<Edge>("Edge", init<Node&,Node&>())
    .add_property("n0",&Edge::N0,return_internal_reference<>());

(the class Node is exposed right before) I get the error:

error: cannot create pointer to reference member ‘Edge::n0’

I could make the accessor return a copy of n0, and it would work fine (tested). However, if n0 were to be really heavy I would prefer for performance issues to return a const reference rather than a copy.

Can anyone explain to me what is wrong with what I am doing? I am pretty new to C++ and Boost.Python and admittedly don't understand much about the call policies yet.


Solution

  • 2 years later, you can still do it via add_property if you use boost::python::make_function:

    class_<Edge>("Edge", init<Node&,Node&>())
        .add_property(
            "n0", 
            make_function(&Edge::N0, return_value_policy<reference_existing_object>()));