Note that there are some explanatory texts on larger screens.

plurals
  1. POBoost.Python - How to return by reference?
    primarykey
    data
    text
    <p>I'm using Boost.Python to create Python modules from C++ classes. And I ran into a problem with references.</p> <p>Condider the following case where I have a class Foo with overloaded get methods that can either return by value or reference.</p> <p>Specifying that the return by value should be used was easy once I typedefed a signature. But I think it should be possible return a reference as well by using a <code>return_value_policy</code>. However, using what seemed appropriate (<a href="http://www.boost.org/doc/libs/1_40_0/libs/python/doc/v2/reference_existing_object.html" rel="noreferrer">doc</a>); <code>return_value_policy&lt;reference_existing_object&gt;</code> did not seem to work. </p> <p>Have I misunderstood what it does?</p> <pre><code>struct Foo { Foo(float x) { _x = x; } float&amp; get() { return _x; } float get() const { return _x; } private: float _x; }; // Wrapper code BOOST_PYTHON_MODULE(my_module) { using namespace boost::python; typedef float (Foo::*get_by_value)() const; typedef float&amp; (Foo::*get_by_ref)(); class_&lt;Foo&gt;("Foo", init&lt;float&gt;()) .def("get", get_by_value(&amp;Foo::get)) .def("get_ref", get_by_ref(&amp;Foo::get), return_value_policy&lt;reference_existing_object&gt;())//Doesn't work ; } </code></pre> <p>Note: I know it could be dangerous to reference existing object without life-time managing.</p> <p><strong>Update:</strong><br> It looks like it works for objects but not basic data types.<br> Take this revised example:</p> <pre><code>struct Foo { Foo(float x) { _x = x; } float&amp; get() { return _x; } float get() const { return _x; } void set( float f ){ _x = f;} Foo&amp; self(){return *this;} private: float _x; }; // Wrapper code using namespace boost::python; BOOST_PYTHON_MODULE(my_module) { typedef float (Foo::*get_by_value)() const; class_&lt;Foo&gt;("Foo", init&lt;float&gt;()) .def("get", get_by_value(&amp;Foo::get)) .def("get_self", &amp;Foo::self, return_value_policy&lt;reference_existing_object&gt;()) .def("set", &amp;Foo::set); ; } </code></pre> <p>Which in a test gave the expected result:</p> <pre><code>&gt;&gt;&gt; foo1 = Foo(123) &gt;&gt;&gt; foo1.get() 123.0 &gt;&gt;&gt; foo2 = foo1.get_self() &gt;&gt;&gt; foo2.set(1) &gt;&gt;&gt; foo1.get() 1.0 &gt;&gt;&gt; id(foo1) == id(foo2) False </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload