]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | [section boost/python/copy_non_const_reference.hpp] |
2 | [section Class `copy_non_const_reference`] | |
3 | `copy_non_const_reference` is a model of [link concepts.resultconverter.resultconvertergenerator_concept ResultConverterGenerator] which can be used to wrap C++ functions returning a reference-to-non-const type such that the referenced value is copied into a new Python object. | |
4 | `` | |
5 | namespace boost { namespace python | |
6 | { | |
7 | struct copy_non_const_reference | |
8 | { | |
9 | template <class T> struct apply; | |
10 | }; | |
11 | }} | |
12 | `` | |
13 | [endsect] | |
14 | [section Class `copy_non_const_reference` metafunctions] | |
15 | ``template <class T> struct apply`` | |
16 | [variablelist | |
17 | [[Requires][`T` is `U &` for some non-const `U`.]] | |
18 | [[Returns][`typedef to_python_value<T> type`;]] | |
19 | ] | |
20 | [endsect] | |
21 | [section Example] | |
22 | C++ module definition: | |
23 | `` | |
24 | #include <boost/python/module.hpp> | |
25 | #include <boost/python/class.hpp> | |
26 | #include <boost/python/copy_non_const_reference.hpp> | |
27 | #include <boost/python/return_value_policy.hpp> | |
28 | ||
29 | // classes to wrap | |
30 | struct Bar { int x; } | |
31 | ||
32 | struct Foo { | |
33 | Foo(int x) : { b.x = x; } | |
34 | Bar& get_bar() { return b; } | |
35 | private: | |
36 | Bar b; | |
37 | }; | |
38 | ||
39 | // Wrapper code | |
40 | using namespace boost::python; | |
41 | BOOST_PYTHON_MODULE(my_module) | |
42 | { | |
43 | class_<Bar>("Bar"); | |
44 | ||
45 | class_<Foo>("Foo", init<int>()) | |
46 | .def("get_bar", &Foo::get_bar | |
47 | , return_value_policy<copy_non_const_reference>()) | |
48 | ; | |
49 | } | |
50 | `` | |
51 | Python code: | |
52 | `` | |
53 | >>> from my_module import * | |
54 | >>> f = Foo(3) # create a Foo object | |
55 | >>> b = f.get_bar() # make a copy of the internal Bar object | |
56 | `` | |
57 | [endsect] | |
58 | [endsect] |