return_by_value.qbk 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. [section boost/python/return_by_value.hpp]
  2. [section Class `return_by_value`]
  3. `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.
  4. ``
  5. namespace boost { namespace python
  6. {
  7. struct return_by_value
  8. {
  9. template <class T> struct apply;
  10. };
  11. }}
  12. ``
  13. [endsect]
  14. [section Class `return_by_value` metafunctions]
  15. ``template <class T> struct apply``
  16. [variablelist
  17. [[Returns][`typedef to_python_value<T> type;`]]
  18. ]
  19. [endsect]
  20. [section Example]
  21. In C++:
  22. ``
  23. #include <boost/python/module.hpp>
  24. #include <boost/python/class.hpp>
  25. #include <boost/python/return_by_value.hpp>
  26. #include <boost/python/return_value_policy.hpp>
  27. // classes to wrap
  28. struct Bar { };
  29. Bar global_bar;
  30. // functions to wrap:
  31. Bar b1();
  32. Bar& b2();
  33. Bar const& b3();
  34. // Wrapper code
  35. using namespace boost::python;
  36. template <class R>
  37. void def_void_function(char const* name, R (*f)())
  38. {
  39. def(name, f, return_value_policy<return_by_value>());
  40. }
  41. BOOST_PYTHON_MODULE(my_module)
  42. {
  43. class_<Bar>("Bar");
  44. def_void_function("b1", b1);
  45. def_void_function("b2", b2);
  46. def_void_function("b3", b3);
  47. }
  48. ``
  49. Python code:
  50. ``
  51. >>> from my_module import *
  52. >>> b = b1() # each of these calls
  53. >>> b = b2() # creates a brand
  54. >>> b = b3() # new Bar object
  55. ``
  56. [endsect]
  57. [endsect]