pytype_function.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright Joel de Guzman 2004. Distributed under the Boost
  2. // Software License, Version 1.0. (See accompanying
  3. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4. #include <boost/python/module.hpp>
  5. #include <boost/python/def.hpp>
  6. #include <boost/python/extract.hpp>
  7. #include <boost/python/to_python_converter.hpp>
  8. #include <boost/python/class.hpp>
  9. using namespace boost::python;
  10. struct A
  11. {
  12. };
  13. struct B
  14. {
  15. A a;
  16. B(const A& a_):a(a_){}
  17. };
  18. // Converter from A to python int
  19. struct BToPython
  20. #ifndef BOOST_PYTHON_NO_PY_SIGNATURES
  21. : converter::to_python_target_type<A> //inherits get_pytype
  22. #endif
  23. {
  24. static PyObject* convert(const B& b)
  25. {
  26. return boost::python::incref(boost::python::object(b.a).ptr());
  27. }
  28. };
  29. // Conversion from python int to A
  30. struct BFromPython
  31. {
  32. BFromPython()
  33. {
  34. boost::python::converter::registry::push_back(
  35. &convertible,
  36. &construct,
  37. boost::python::type_id< B >()
  38. #ifndef BOOST_PYTHON_NO_PY_SIGNATURES
  39. , &converter::expected_from_python_type<A>::get_pytype//convertible to A can be converted to B
  40. #endif
  41. );
  42. }
  43. static void* convertible(PyObject* obj_ptr)
  44. {
  45. extract<const A&> ex(obj_ptr);
  46. if (!ex.check()) return 0;
  47. return obj_ptr;
  48. }
  49. static void construct(
  50. PyObject* obj_ptr,
  51. boost::python::converter::rvalue_from_python_stage1_data* data)
  52. {
  53. void* storage = (
  54. (boost::python::converter::rvalue_from_python_storage< B >*)data)-> storage.bytes;
  55. extract<const A&> ex(obj_ptr);
  56. new (storage) B(ex());
  57. data->convertible = storage;
  58. }
  59. };
  60. B func(const B& b) { return b ; }
  61. BOOST_PYTHON_MODULE(pytype_function_ext)
  62. {
  63. to_python_converter< B , BToPython,true >(); //has get_pytype
  64. BFromPython();
  65. class_<A>("A") ;
  66. def("func", &func);
  67. }
  68. #include "module_tail.cpp"