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 5 #include <boost/python/module.hpp> 6 #include <boost/python/def.hpp> 7 #include <boost/python/extract.hpp> 8 #include <boost/python/to_python_converter.hpp> 9 #include <boost/python/class.hpp> 10 11 using namespace boost::python; 12 13 struct A 14 { 15 }; 16 17 struct B 18 { 19 A a; BB20 B(const A& a_):a(a_){} 21 }; 22 23 // Converter from A to python int 24 struct BToPython 25 #ifndef BOOST_PYTHON_NO_PY_SIGNATURES 26 : converter::to_python_target_type<A> //inherits get_pytype 27 #endif 28 { convertBToPython29 static PyObject* convert(const B& b) 30 { 31 return boost::python::incref(boost::python::object(b.a).ptr()); 32 } 33 }; 34 35 // Conversion from python int to A 36 struct BFromPython 37 { BFromPythonBFromPython38 BFromPython() 39 { 40 boost::python::converter::registry::push_back( 41 &convertible, 42 &construct, 43 boost::python::type_id< B >() 44 #ifndef BOOST_PYTHON_NO_PY_SIGNATURES 45 , &converter::expected_from_python_type<A>::get_pytype//convertible to A can be converted to B 46 #endif 47 ); 48 } 49 convertibleBFromPython50 static void* convertible(PyObject* obj_ptr) 51 { 52 extract<const A&> ex(obj_ptr); 53 if (!ex.check()) return 0; 54 return obj_ptr; 55 } 56 constructBFromPython57 static void construct( 58 PyObject* obj_ptr, 59 boost::python::converter::rvalue_from_python_stage1_data* data) 60 { 61 void* storage = ( 62 (boost::python::converter::rvalue_from_python_storage< B >*)data)-> storage.bytes; 63 64 extract<const A&> ex(obj_ptr); 65 new (storage) B(ex()); 66 data->convertible = storage; 67 } 68 }; 69 70 func(const B & b)71B func(const B& b) { return b ; } 72 73 BOOST_PYTHON_MODULE(pytype_function_ext)74BOOST_PYTHON_MODULE(pytype_function_ext) 75 { 76 to_python_converter< B , BToPython,true >(); //has get_pytype 77 BFromPython(); 78 79 class_<A>("A") ; 80 81 def("func", &func); 82 83 } 84 85 #include "module_tail.cpp" 86