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 MAKE_INSTANCE_DWA200296_HPP
6 # define MAKE_INSTANCE_DWA200296_HPP
8 # include <boost/python/detail/prefix.hpp>
9 # include <boost/python/object/instance.hpp>
10 # include <boost/python/converter/registered.hpp>
11 # include <boost/python/detail/decref_guard.hpp>
12 # include <boost/python/detail/type_traits.hpp>
13 # include <boost/python/detail/none.hpp>
14 # include <boost/mpl/assert.hpp>
15 # include <boost/mpl/or.hpp>
17 namespace boost { namespace python { namespace objects {
19 template <class T, class Holder, class Derived>
20 struct make_instance_impl
22 typedef objects::instance<Holder> instance_t;
25 static inline PyObject* execute(Arg& x)
27 BOOST_MPL_ASSERT((mpl::or_<boost::python::detail::is_class<T>,
28 boost::python::detail::is_union<T> >));
30 PyTypeObject* type = Derived::get_class_object(x);
33 return python::detail::none();
35 PyObject* raw_result = type->tp_alloc(
36 type, objects::additional_instance_size<Holder>::value);
40 python::detail::decref_guard protect(raw_result);
42 instance_t* instance = (instance_t*)raw_result;
44 // construct the new C++ object and install the pointer
45 // in the Python object.
46 Holder *holder =Derived::construct(instance->storage.bytes, (PyObject*)instance, x);
47 holder->install(raw_result);
49 // Note the position of the internally-stored Holder,
50 // for the sake of destruction
51 const size_t offset = reinterpret_cast<size_t>(holder) -
52 reinterpret_cast<size_t>(instance->storage.bytes) + offsetof(instance_t, storage);
53 Py_SET_SIZE(instance, offset);
55 // Release ownership of the python object
63 template <class T, class Holder>
65 : make_instance_impl<T, Holder, make_instance<T,Holder> >
68 static inline PyTypeObject* get_class_object(U&)
70 return converter::registered<T>::converters.get_class_object();
73 static inline Holder* construct(void* storage, PyObject* instance, reference_wrapper<T const> x)
75 size_t allocated = objects::additional_instance_size<Holder>::value;
76 void* aligned_storage = ::boost::alignment::align(boost::python::detail::alignment_of<Holder>::value,
77 sizeof(Holder), storage, allocated);
78 return new (aligned_storage) Holder(instance, x);
83 }}} // namespace boost::python::object
85 #endif // MAKE_INSTANCE_DWA200296_HPP