shared_ptr_from_python.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright David Abrahams 2002.
  2. // Distributed under the Boost Software License, Version 1.0. (See
  3. // accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef SHARED_PTR_FROM_PYTHON_DWA20021130_HPP
  6. # define SHARED_PTR_FROM_PYTHON_DWA20021130_HPP
  7. # include <boost/python/handle.hpp>
  8. # include <boost/python/converter/shared_ptr_deleter.hpp>
  9. # include <boost/python/converter/from_python.hpp>
  10. # include <boost/python/converter/rvalue_from_python_data.hpp>
  11. # include <boost/python/converter/registered.hpp>
  12. #ifndef BOOST_PYTHON_NO_PY_SIGNATURES
  13. # include <boost/python/converter/pytype_function.hpp>
  14. #endif
  15. # include <boost/shared_ptr.hpp>
  16. namespace boost { namespace python { namespace converter {
  17. template <class T>
  18. struct shared_ptr_from_python
  19. {
  20. shared_ptr_from_python()
  21. {
  22. converter::registry::insert(&convertible, &construct, type_id<shared_ptr<T> >()
  23. #ifndef BOOST_PYTHON_NO_PY_SIGNATURES
  24. , &converter::expected_from_python_type_direct<T>::get_pytype
  25. #endif
  26. );
  27. }
  28. private:
  29. static void* convertible(PyObject* p)
  30. {
  31. if (p == Py_None)
  32. return p;
  33. return converter::get_lvalue_from_python(p, registered<T>::converters);
  34. }
  35. static void construct(PyObject* source, rvalue_from_python_stage1_data* data)
  36. {
  37. void* const storage = ((converter::rvalue_from_python_storage<shared_ptr<T> >*)data)->storage.bytes;
  38. // Deal with the "None" case.
  39. if (data->convertible == source)
  40. new (storage) shared_ptr<T>();
  41. else
  42. {
  43. boost::shared_ptr<void> hold_convertible_ref_count(
  44. (void*)0, shared_ptr_deleter(handle<>(borrowed(source))) );
  45. // use aliasing constructor
  46. new (storage) shared_ptr<T>(
  47. hold_convertible_ref_count,
  48. static_cast<T*>(data->convertible));
  49. }
  50. data->convertible = storage;
  51. }
  52. };
  53. }}} // namespace boost::python::converter
  54. #endif // SHARED_PTR_FROM_PYTHON_DWA20021130_HPP