summaryrefslogtreecommitdiff
path: root/libs/python/doc/reference/return_by_value.qbk
blob: 2b8b7887ca58f6104c1a8dd978e7a587d7b22176 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
[section boost/python/return_by_value.hpp]
[section Class `return_by_value`]
`return_by_value` is a model of [link concepts.resultconverter.resultconvertergenerator_concept ResultConverterGenerator] which can be used to wrap C++ functions returning any reference or value type such that the return value is copied into a new Python object.
``
namespace boost { namespace python
{
    struct return_by_value
    {
        template <class T> struct apply;
    };
}}
``
[endsect]
[section Class `return_by_value` metafunctions]
``template <class T> struct apply``
[variablelist
[[Returns][`typedef to_python_value<T> type;`]]
]
[endsect]
[section Example]
In C++:
``
#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/python/return_by_value.hpp>
#include <boost/python/return_value_policy.hpp>

// classes to wrap
struct Bar { };

Bar global_bar;

// functions to wrap:
Bar b1();
Bar& b2();
Bar const& b3();

// Wrapper code
using namespace boost::python;
template <class R>
void def_void_function(char const* name, R (*f)())
{
   def(name, f, return_value_policy<return_by_value>());
}

BOOST_PYTHON_MODULE(my_module)
{
    class_<Bar>("Bar");
    def_void_function("b1", b1);
    def_void_function("b2", b2);
    def_void_function("b3", b3);
}
``
Python code:
``
>>> from my_module import *
>>> b = b1() # each of these calls
>>> b = b2() # creates a brand
>>> b = b3() # new Bar object
``
[endsect]
[endsect]