#include #include // for auto_ptr template struct AutoConverter { AutoConverter(); // Conversion "to Python" method. // // If this is not specialized, it calls the toObject() factory which is // expected to return a Boost.Python container type for the Python // representation of the object. static PyObject* convert( T const& s ); // Conversion "to Python" method. // // Override and build and return a Boost.Python container type to represent // the Python object. static python::object toObject( T const& s ); // Specialize the following method to return whether the type conversion can // be applied or not. static void* convertible( PyObject* ); // Main method for "from Python" method--don't override, it contains the // memory allocation. static void construct( PyObject* obj_ptr, python::converter::rvalue_from_python_stage1_data* data ); // Conversion "from Python" method. // // Override this method to convert from the PyObject* into the already // allocated memory block (use in-place allocation). static void fromPython( PyObject* obj_ptr, void* memblock ); // Conversion "from Python" method. // // Override this method to convert from the Boost.Python object into the // already allocated memory block (use in-place allocation). static void fromObject( python::object& obj, void* memblock ); }; template AutoConverter::AutoConverter() { // Register to-python converter. python::to_python_converter< T, AutoConverter >(); // Register from-python converter. python::converter::registry::push_back( &convertible, &construct, python::type_id() ); } template PyObject* AutoConverter::convert( T const& s ) { return python::incref( toObject( s ).ptr() ); } template void* AutoConverter::convertible( PyObject* obj_ptr ) { // Default implementation refuses conversion. return 0; } template void AutoConverter::construct( PyObject* obj_ptr, python::converter::rvalue_from_python_stage1_data* data ) { // This should be exception-safe if the conversion fails (i.e. auto_ptr will // take care of freeing memory. std::auto_ptr storage( reinterpret_cast< python::converter::rvalue_from_python_storage* >( data )->storage.bytes ); fromPython( obj_ptr, storage.get() ); data->convertible = storage.release(); } template void AutoConverter::fromPython( PyObject* obj_ptr, void* memblock ) { python::handle<> h( obj_ptr ); python::object obj( h ); fromObject( obj, memblock ); } template void AutoConverter::fromObject( python::object& obj, void* memblock ) { // This method must be overriden or not called. assert( false ); }