call_method.qbk 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. [section boost/python/call_method.hpp]
  2. [section Introduction]
  3. <boost/python/call_method.hpp> defines the call_method family of overloaded function templates, used to invoke callable attributes of Python objects from C++.
  4. [endsect]
  5. [section Function `call_method`]
  6. ``
  7. template <class R, class A1, class A2, ... class An>
  8. R call_method(PyObject* self, char const* method, A1 const&, A2 const&, ... An const&)
  9. ``
  10. [variablelist
  11. [[Requires][`R` is a pointer type, reference type, or a complete type with an accessible copy constructor]]
  12. [[Effects][Invokes `self.method(a1, a2, ...an)` in Python, where `a1...an` are the arguments to `call_method()`, converted to Python objects. For a complete semantic description, see this page.]]
  13. [[Returns][The result of the Python call, converted to the C++ type `R`.]]
  14. [[Rationale][`call_method` is critical to implementing C++ virtual functions which are overridable in Python, as shown by the example below.]]
  15. ]
  16. [endsect]
  17. [section Example]
  18. The following C++ illustrates the use of `call_method` in wrapping a class with a virtual function that can be overridden in Python:
  19. C++ Module Definition
  20. ``
  21. #include <boost/python/module.hpp>
  22. #include <boost/python/class.hpp>
  23. #include <boost/utility.hpp>
  24. #include <cstring>
  25. // class to be wrapped
  26. class Base
  27. {
  28. public:
  29. virtual char const* class_name() const { return "Base"; }
  30. virtual ~Base();
  31. };
  32. bool is_base(Base* b)
  33. {
  34. return !std::strcmp(b->class_name(), "Base");
  35. }
  36. // Wrapper code begins here
  37. using namespace boost::python;
  38. // Callback class
  39. class Base_callback : public Base
  40. {
  41. public:
  42. Base_callback(PyObject* self) : m_self(self) {}
  43. char const* class_name() const { return call_method<char const*>(m_self, "class_name"); }
  44. char const* Base_name() const { return Base::class_name(); }
  45. private:
  46. PyObject* const m_self;
  47. };
  48. using namespace boost::python;
  49. BOOST_PYTHON_MODULE(my_module)
  50. {
  51. def("is_base", is_base);
  52. class_<Base,Base_callback, noncopyable>("Base")
  53. .def("class_name", &Base_callback::Base_name)
  54. ;
  55. }
  56. ``
  57. Python code:
  58. ``
  59. >>> from my_module import *
  60. >>> class Derived(Base):
  61. ... def __init__(self):
  62. ... Base.__init__(self)
  63. ... def class_name(self):
  64. ... return self.__class__.__name__
  65. ...
  66. >>> is_base(Base()) # calls the class_name() method from C++
  67. 1
  68. >>> is_base(Derived())
  69. 0
  70. ``
  71. [endsect]
  72. [endsect]